;; -*- mode:scheme -*-
;;
;; A script to restore dbm content
;;
;; Usage: gosh dbm/restore [-i <infile>][-t <type>] <dbmname>
;;

(use gauche.parseopt)
(use dbm)
(use util.match)
(use file.filter)

(define (main args)
  (let-args (cdr args) ([ifile "i=s" #f]
                        [type  "t=y" 'gdbm]
                        [else _ (usage)]
                        . args)
    (let1 class (dbm-type->class type)
      (unless class (exit 1 "dbm type `~a' unknown" type))
      (match args
        [(dbmname) (do-dump dbmname class (or ifile (current-input-port)))]
        [else (usage)]))
    0))

(define (usage)
  (print "Usage: gosh dbm/restore [-i infile][-t type] dbmname")
  (exit 0))

(define (do-dump name class input)
  (let1 dbm (guard (e [else (exit 1 "couldn't create dbm database: ~a"
                                  (~ e'message))])
              (dbm-open class :path name :rw-mode :create))
    (file-filter
     (^(in out)
       (port-for-each
        (^p (if (and (pair? p)
                     (string? (car p))
                     (string? (cdr p)))
              (dbm-put! dbm (car p) (cdr p))
              (warn "invalid entry in input ignored: ~,,,,65s" p)))
        (cut read in)))
     :input input)
    (dbm-close dbm)))


