;; SPDX-License-Identifier: Apache-2.0 ;; SPDX-FileCopyrightText: 2022 Sebastian Crane (ns system (:require [irc] [clojure.data.json :as json] [clj-yaml.core :as yaml])) (defn json-data-reader [key value] (if (= key :games) (into (empty value) (map #(hash-map (first %) (set (second %))) value)) value)) (defn load-state [f] (try (with-open [datafile (clojure.java.io/reader f)] (json/read datafile :value-fn json-data-reader :key-fn keyword)) (catch Exception e nil))) (defn save-state [f data] (try (with-open [datafile (clojure.java.io/writer f)] (json/write data datafile)) (catch Exception e nil))) (defn load-config [f] (try (with-open [datafile (clojure.java.io/reader f)] (yaml/parse-stream datafile)) (catch Exception e nil))) (defn system [] {:config nil :state nil :irc nil}) (defn start [system] (let [config (load-config "config.yaml") state (atom (load-state (:data-file config))) irc (irc/new-irc-connection state config)] (irclj.core/join irc (get-in config [:irc :channel])) {:config config :state state :irc irc})) (defn stop [system] (do (save-state (get-in system [:config :data-file]) (deref (:state system))) (irclj.core/quit (system :irc)))) (defn restart [system-atom] (do (swap! system-atom stop) (reset! system-atom (system)) (swap! system-atom start))) (defn -main [& args] (let [main-system (atom (system/system))] (swap! main-system system/start) (.addShutdownHook (Runtime/getRuntime) (Thread. (partial swap! main-system stop)))))