(use-modules (ice-9 rdelim))

;general helper functions
(define (read-fold proc initial . args)
  (let ((port (if (null? args) (current-input-port) (car args))))
    (let loop ((line (read-line port))
	       (result initial))
      (if (eof-object? line)
          result
          (loop (read-line port) (proc line result))))))

(define db
  (let* ((db-table
	  (with-input-from-file "/var/cache/printer-drivers/dump"
				(lambda ()
				  (read-fold
				    (lambda (line table)
				      (let* ((sp (string-cut line #\;))
					     (key (car sp))
					     (handle (hash-get-handle table key))
					     (val (or (and handle (cdr handle)) '())))
					(hash-set! table key (cons  (cons (cadr sp) (caddr sp))
								    val))
					table))
				    (make-hash-table 10)))))
	 (keys (hash-fold (lambda (x y z) (cons x z)) '() db-table)))
    (cons keys db-table)))

(define (read-printers-models vendor table)
  (let ((models (hash-get-handle table vendor)))
    (if models
      (map (lambda (x) (list (car x))) (cdr models))
      '(error "unknown vendor"))))

(define (read-printers-driver vendor model table)
  (let ((models (hash-get-handle table vendor)))
    (if models
      (let ((info (assoc model (cdr models))))
	(if info (list 'id (cdr info))
	  '(error "unknown model")))
      '(error "unknown vendor"))))

(object
 #f
 ((list self objects options)
  (case (length objects)
    ((0) (map list (car db)))
    ((1) (read-printers-models (car objects) (cdr db)))
    (else '(error "wrong number of arguments"))))
 ((read self objects options)
  (if (>= (length objects) 2)
      (read-printers-driver (car objects)
                            (string-join (cdr objects) "/") (cdr db))
      '(error "wrong number of arguments"))))
