#!/usr/local/bin/newlisp

(constant 'options
 '(
;("-h" nil "help")
   ("-i:" "ignore-lines.txt" "Name the ignore file.")
   ("-h:" "99-hwdb-stanzas.hwdb" "Name the hwdb stanzas file.")
   ("-o:" "todo.txt" "Name the unhandled rules file.")
   ("-c"  nil "Delete the files first.")
   ))

; Process the command line
(load "command-line.lsp")

(define (logln)
  (write-line 2 (join (map string (args)))))

(unless (member "--" (main-args))
  (logln "Usage: [ options ] -- rules")
  (dolist (op options)
    (logln "  " (op 0) "X = " (op 2) " (default: " (op 1) ")"))
  (exit 0))

(unless cmdargs
  (logln "No input files")
  (exit 0))

(constant
 'HWDBFILE (option "-h:")
 'TODOFILE (option "-o:")
 'IGNOREFILE (option "-i:")
 'BLURB (when (option "-c")
          (string
           "# THIS FILE IS AUTO-GENERATED BY " cmd0 "\n"
           "# You shouldn't change it by hand.\n"
           "#\n"
           "# Command options: " cmdopts " --\n"
           "# Input rules files:\n"
           (join (map (curry string "#     ") cmdargs) "\n" true)
           "\n"))
 )

(logln "compile-udev-rules: " cmdargs)
(logln "into: " (list HWDBFILE TODOFILE IGNOREFILE))

(when (option "-c")
  (map delete-file (list IGNOREFILE TODOFILE HWDBFILE))
  )

; Load and parse rules files, into <RULES>
; This will exit if there are no rules.
(load "load-rules.lsp")

; Load up the ignoreable rule lines
(load "ignore.lsp")

; Reduce to interesting rules
(logln "Initial rules count: " (length RULES))

(setf RULES (filter action-rule? RULES))
(logln "Action rules: " (length RULES))

(setf RULES (clean ignore-rule? RULES))
(logln "After ignored: " (length RULES))

; Load classification logic
(load "classifications.lsp")

(define (key-part rule)
  (select rule (index action-term? rule)))

(setf COUNT 0)
(dolist (rule RULES)
  (cond ((setf hwdb (hwdb-stanza rule))
         (when (and (= COUNT) BLURB) (append-file HWDBFILE BLURB))
         (append-file HWDBFILE hwdb)
         (add-ignore-rule rule)
         (inc COUNT))
        (true
         (append-file TODOFILE
                      (string (lookup "LINE" rule) "\n"
                              (string (select rule (index action-term? rule)))
                              "\n\n")))))
(logln "Resulting hwdb rules: " COUNT)
(logln "Remaining rules: " (- (length RULES) COUNT))
; rewrite the ignore file
(save-ignore)
(exit 0)
