A simple program for making sure folders are mounted. Eventually.

core.clj 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. (ns ensure-mounted.core
  2. (:require [clojure.java.shell :as sh]
  3. [clojure.set :as set]
  4. [clojure.string :as str])
  5. (:import (java.io BufferedReader FileInputStream InputStreamReader))
  6. (:gen-class))
  7. (defmacro def-> [n & body] `(defn ~n [top#] (-> top# ~@body)))
  8. (defmacro def->> [n & body] `(defn ~n [top#] (->> top# ~@body)))
  9. (def start-ensure? (partial = "#== ensure-mounted"))
  10. (def end-ensure? (partial = "#== ensure-mounted-end"))
  11. (def-> mount-point (str/split #" ") second)
  12. (def mount-points (comp (partial apply hash-set) (partial map mount-point)))
  13. (def mount! (partial sh/sh "mount"))
  14. (def-> reader FileInputStream. InputStreamReader. BufferedReader.)
  15. (defn lines [filename] (with-open [r (reader filename)] (doall (line-seq r))))
  16. (defn qualify-line [{:keys [active?] :as result} line]
  17. (cond
  18. (start-ensure? line) (assoc result :active? true)
  19. (end-ensure? line) (assoc result :active? false)
  20. active? (update result :lines conj line)
  21. :else result))
  22. (def->> desired-block (reduce qualify-line {:active? false, :lines []}) :lines)
  23. (defn add-mount-result [results {:keys [exit err]}]
  24. (if (= 0 exit)
  25. results
  26. (-> results (assoc :failed? true) (update :errs conj err))))
  27. (defn mount-missing! []
  28. (let [existing (-> "/proc/mounts" lines mount-points)
  29. desired (-> "/etc/fstab" lines desired-block mount-points)
  30. necessary (set/difference desired existing)
  31. results (doall (map mount! necessary))]
  32. (if (seq desired)
  33. (reduce add-mount-result {:failed? false, :errs []} results)
  34. {:failed? true
  35. :errs ["Unable to find any mount points. Is your fstab annotated?"]})))
  36. (defn -main [& _]
  37. (let [{:keys [failed? errs]} (mount-missing!)]
  38. (when failed?
  39. (binding [*out* *err*] (-> errs str/join println))
  40. (System/exit 1)))
  41. (System/exit 0))