(ns sydnix-cli.main
  (:require [babashka.cli :as cli]
            [sydnix-cli.commands.rebuild :as rebuild]
            [sydnix-cli.commands.help :as help]
            [clojure.pprint :refer [pprint]]))

(defn help [opts]
  (println "Hellllpp"))

(def cli-table
  [rebuild/command
   help/command
   ;; Assume help command when no subcommand is given.
   (assoc help/command :cmds [])])

(defmacro stderr [& body]
  `(binding [*out* *err*]
     ~@body))

(defn error-fn [{:keys [spec type cause msg option] :as data}]
  (if (= :org.babashka/cli type)
    (stderr (printf "Error: %s\n" msg))
    (stderr
     (println "a mysterious error has occured...")
     (pprint data))))

(defn -main [& args]
  (cli/dispatch cli-table args
                {:restrict true
                 :error-fn #(do (error-fn %)
                                (stderr (flush))
                                (System/exit 1))})
  (shutdown-agents))
