(ns build
  "tools.build configuration for building uberjars for each service."
  (:require [clojure.tools.build.api :as b]))

(def version "0.1.0")

(defn- module-config [module]
  (let [class-dir (str module "/target/classes")
        basis     (b/create-basis {:aliases [(keyword module)]})]
    {:module    module
     :class-dir class-dir
     :uber-file (str module "/target/" module ".jar")
     :basis     basis
     :main      (symbol (str "ajet.chat."
                              (case module
                                "api"     "api.core"
                                "auth-gw" "auth-gw.core"
                                "web-sm"  "web.core"
                                "tui-sm"  "tui-sm.core"
                                "cli"     "cli.core")))}))

(defn uber
  "Build an uberjar for a service module.

   Usage: clj -T:build uber :module api
          clj -T:build uber :module auth-gw"
  [{:keys [module]}]
  (let [{:keys [class-dir uber-file basis main]} (module-config (name module))]
    (println "Building uberjar for" (name module) "...")
    (b/delete {:path class-dir})
    (b/copy-dir {:src-dirs   ["shared/src" "shared/resources"
                               (str (name module) "/src")
                               (str (name module) "/resources")]
                 :target-dir class-dir})
    (b/compile-clj {:basis     basis
                    :src-dirs  ["shared/src" (str (name module) "/src")]
                    :class-dir class-dir})
    (b/uber {:class-dir class-dir
             :uber-file uber-file
             :basis     basis
             :main      main})
    (println "Built:" uber-file)))

(defn clean
  "Clean build artifacts for a module."
  [{:keys [module]}]
  (b/delete {:path (str (name module) "/target")}))

(defn clean-all
  "Clean all build artifacts."
  [_]
  (doseq [m ["api" "auth-gw" "web-sm" "tui-sm" "cli"]]
    (b/delete {:path (str m "/target")})))
