 
 (import-logging)
 
-(defn creds [] (hypervisor :aws))
+(defn creds [] (dissoc (hypervisor :aws) :ostemplates))
 
 (defn wait-for-status [instance req-stat timeout]
   "Waiting for ec2 machine status timeout is in mili"

      (s/partial-system (spec :system-id) 
        {:machine {:ip (pubdns-to-ip ec2-host)}}))))

(defn set-hostname [spec endpoint instance-id user]
  "Uses a generic method of setting hostname in Linux (see http://www.debianadmin.com/manpages/sysctlmanpage.txt)
   Note that in ec2 both Centos and Ubuntu use sudo!"
  (let [{:keys [hostname domain]} (spec :machine) 
        remote {:host (pub-dns endpoint instance-id) :user user}]
    (execute (<< "echo kernel.hostname=~{hostname} | sudo tee -a /etc/sysctl.conf") remote )
    (execute (<< "echo kernel.domainname=\"~{hostname}.~{domain}\" | sudo tee -a /etc/sysctl.conf") remote )
    (execute (<< "echo 127.0.1.1 ~{hostname}.~{domain} ~{hostname} | sudo tee -a /etc/hosts") remote )
    (execute (<< "echo ~{hostname} | sudo tee /etc/hostname") remote )
    (execute "sudo sysctl -e -p" remote) 
    (with-ctx ec2/create-tags [(instance-desc endpoint instance-id :id)] {:Name hostname})
    ))

    (do ~@body) 
    (throw+ {:type ::aws:missing-id :message "Instance id not found"}))) 

(defn image-id [machine]
  (hypervisor :aws :ostemplates (machine :os) :ami))

(defn handle-volumes 
   "attached and waits for ebs volumes" 
   [{:keys [aws machine] :as spec} endpoint instance-id]
  (when (= (image-desc endpoint (image-id machine) :root-device-type) "ebs")
    (wait-for-attach endpoint instance-id [10 :minute]))
  (let [zone (instance-desc endpoint instance-id :placement :availability-zone)]
    (doseq [{:keys [device size]} (aws :volumes)]
      (let [{:keys [volumeId]} (with-ctx ebs/create-volume size zone)]
        (wait-for {:timeout [10 :minute]} #(= "available" (with-ctx ebs/state volumeId))
           {:type ::aws:ebs-volume-availability :message "Failed to wait for ebs volume to become available"})
