 (ns freenas.provider
   "Freenas jails provider"
   (:require 
+    [supernal.core :refer (ns- lifecycle run execute env)]
     [taoensso.timbre :as timbre]
     [clojure.core.strint :refer (<<)] 
     [celestial.provider :refer (wait-for-ssh mappings wait-for)]

    [freenas.validations :refer [validate-provider jail-mappings]]
    [slingshot.slingshot :refer  [throw+]]
    [celestial.persistency.systems :as s]
    [celestial.common :refer (import-logging)]
    [org.httpkit.client :as client]
    [celestial.core :refer (Vm)] 
    [celestial.model :refer (hypervisor translate vconstruct)])
 )

(timbre/refer-timbre)

  (let [js (call client/get "jails/jails/") ]
    (first (filter #(= (:jail_host %) host) js))))

(def jexec "/usr/sbin/jexec" )

(def sed "/usr/bin/sed")

(ns- jail
  (task enable-root-ssh
     (let [{:keys [host]} args]
       (run (<< "~{jexec} ~{host} ~{sed} -i.bak 's/^sshd_enable=.*/sshd_enable=\"YES\"/' /etc/rc.conf"))
       (run (<< "~{jexec} ~{host} ~{sed} -i.bak 's/^#PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config"))
       (run (<< "~{jexec} ~{host} /etc/rc.d/sshd start"))))

  (task add-ssh-key
    (let [{:keys [host]} args pub (clojure.string/trim-newline (slurp (get* :ssh :public-key-path)))]
      (run (<< "~{jexec} ~{host} mkdir /root/.ssh"))
      (run (<< "~{jexec} ~{host} sh -c  'pub=\"~{pub}\"; echo \"$pub\" | cat > /root/.ssh/authorized_keys'"))
      (run (<< "~{jexec} ~{host} chmod 700 /root/.ssh && chmod 600 /root/.ssh/authorized_keys")))))

(lifecycle prepare-jail {:doc "preparing jail with ssh and celestial key"}
   {jail/add-ssh-key #{} 
    jail/enable-root-ssh #{jail/add-ssh-key}})

(defn enable-ssh [host]
  (let [roles {:roles {:jails #{(hypervisor* :freenas)}}}]
     (execute prepare-jail {:host host} :jails :env roles)))

(defrecord Jail [spec]
  Vm
