(ns sydnix-cli.commands.util.mangen
  (:require
   [asciidoc.render]
   [babashka.fs :as fs]
   [babashka.process :as p]
   [clojure.java.io :as io]
   [clojure.spec.alpha :as s]
   [clojure.string :as str]
   [sydnix-cli.mangen :as mangen]
   [sydnix-cli.cli-table :refer [*cli-table]]
   [sydnix-cli.commands.help :refer [adorn-with-help-option*]]
   [sydnix-cli.prelude :as prelude]))

(defn command-fn [{:keys [yes output-directory]}]
  (if (or yes
          (prelude/y-or-n? (format "Write a bunch of man pages to %s?"
                                   output-directory)))
    (doseq [cmd-spec (deref *cli-table)]
      (let [man-file-name (fs/file
                           output-directory
                           (str (str/join "-" (cons "sydnix" (:cmds cmd-spec)))
                                ".1"))]
        (with-open [man-file (io/writer man-file-name)]
          (mangen/write-man-for-command cmd-spec :out man-file))
        (printf "wrote %s\n" man-file-name)
        (flush)))
    (System/exit 1)))

(def command-options-spec
  {:output-directory {:coerce :string
                      :ref "DIRECTORY"
                      :alias :o
                      :desc "Directory to which the generated man pages will be
                      written."
                      :require true
                      :validate fs/directory?}
   :yes {:coerce :bool
         :desc "Don't ask for confirmation."
         :default false}})

(def command
  (adorn-with-help-option*
   {:cmds ["util" "mangen"]
    :desc "Generate man pages for each subcommand of `sydnix`."
    :fn command-fn
    :spec command-options-spec}))
