#!/usr/bin/env scheme-script
#!r6rs

(import
  (rnrs)
  (fs fatfs)
  (fs fatfs port-device)
  (fs fatfs cli))

(define (usage)
  (display "mmd -i IMAGE DIRECTORY...\n")
  (display "\n")
  (display "-i <image>  FAT image file\n")
  (display "-h          print this help\n"))

(define img-path #f)
(define dirs '())

(let loop-args ((args (cdr (command-line))))
  (unless (null? args)
    (let ((arg (car args))
          (rest (cdr args)))
      (cond
        ((or (equal? arg "-h") (equal? arg "--help"))
         (usage)
         (exit 0))
        ((equal? arg "-i")
         (when (null? rest)
           (display "mmd: -i argument missing a value\n")
           (exit 1))
         (set! img-path (car rest))
         (loop-args (cdr rest)))
        (else
         (set! dirs (append dirs (list arg)))
         (loop-args rest))))))

(unless (and img-path (not (null? dirs)))
  (usage)
  (exit 1))

(define fs (open-fatfs (open-file-fatfs-device img-path #f)))

(for-each
  (lambda (dir)
    (let ((path (string->fat-path dir)))
      (when (null? path)
        (error 'mmd "Cannot create the root directory" dir))
      (when (fatfs-file-exists? fs path)
        (error 'mmd "Directory already exists" dir))
      (fatfs-create-directory fs path)))
  dirs)

(close-fatfs fs)
