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

(import
  (rnrs)
  (fs fatfs)
  (fs fatfs port-device)
  (fs fatfs private compat))

(define (usage)
  (display "fatfs-gen IMAGE_PATH [ARGS]\n")
  (display "\n")
  (display "-t <fat16|fat32> - type of fatfs (default fat16)\n")
  (display "-s <sector-size> - sector size (default 512)\n")
  (display "-h               - print this help\n"))

(when (< (length (command-line)) 2)
  (usage)
  (exit 1))
(when (equal? (cadr (command-line)) "-h")
  (usage)
  (exit 0))

(define img-path (cadr (command-line)))
(define fat-type '(fat16 fat32))
(define sector-size 512)

(let loop-args ([args (cdr (cdr (command-line)))])
  (define (next-arg!)
    (if (not (null? args))
        (let ([arg (car args)])
          (set! args (cdr args))
          arg)
      #f))
  (when (not (null? args))
    (let ([arg (next-arg!)])
      (cond
	((equal? arg "-t")
	 (let ([value (next-arg!)])
	   (cond
	     ((equal? value "fat16") (set! fat-type 'fat16))
	     ((equal? value "fat32") (set! fat-type 'fat32))
	     ((eqv? value #f)
	      (display "-t argument missing a value\n")(exit 1))
	     (else
	      (display "invalid fat-type: ")(display value)(newline)(exit 1)))))
        ((equal? arg "-s")
	 (let ([value (next-arg!)])
	   (when (not value)
	     (display "-s argument missing a value\n")(exit 1))
	   (set! sector-size value)))
      ))
      (loop-args args)))

(define fat (make-fatfs (open-file-fatfs-device img-path sector-size)
			fat-type (fxdiv (file-size img-path) sector-size)))
(create-fatfs! fat)
