 (ns com.narkisr.celestial.puppet-standalone
   "A standalone puppet provisioner"
+  (:import com.jcraft.jsch.JSchException)
   (:use 
     clojure.core.strint
     com.narkisr.celestial.core
     clj-ssh.ssh
+    [taoensso.timbre :only (debug info error warn)]
     [clojure.string :only (join)]
-    ))
+    [slingshot.slingshot :only  [throw+ try+]]))
 
 
+(def ssh-opts {:username "root" :strict-host-key-checking :no})
+
+(defn with-session [host f]
+  (let [session (session (ssh-agent {}) host ssh-opts)] 
+    (try+
+      (with-connection session (f session))
+      (catch #(= (.getMessage %) "Auth fail") e
+        (throw+ {:type ::auth :host host} "Failed to login make sure to ssh-copy-id to the remote host"))
+      )))
+
 (defn put [host file dest]
-  (let [agent (ssh-agent {}) session (session agent host {:username "root"}) ]
-    (with-connection session
+  (with-session host
+    (fn [session]
       (let [channel (ssh-sftp session)]
         (with-channel-connection channel
           (sftp channel {} :put file dest)

    ))

#_(.apply 
  (Standalone. {:host "192.168.5.203"} {:name "puppet-base-env" :src "/home/ronen/code/"}))


  (put (:host server) (str (module :src) (module :name) ".tar.gz")  "/tmp"))

(defn execute [server & batch]
  (let [agent (ssh-agent {}) session (session agent (server :host) ssh-opts) ]
    (with-connection session
      (let [result (ssh session {:in  (join "\n" batch ) })]
        (println result)))))
