 (ns circle.backend.ec2
   (:use [circle.aws-credentials :only (aws-credentials)])
   (:use [clojure.tools.logging :only (infof)])
+  (:use [clojure.core.incubator :only (-?>)])
   (:import com.amazonaws.services.ec2.AmazonEC2Client
            (com.amazonaws.services.ec2.model DescribeInstancesResult
                                              TerminateInstancesRequest

  (->>
   (reservations)
   (mapcat :instances)
   (map bean)))
  
(defn all-instance-ids []
  (map :instanceId (instances)))


(defn delete-keypair
  [name]
  (println "deleting keypair" name)
  (with-ec2-client client
    (-> client
        (.deleteKeyPair (DeleteKeyPairRequest. name)))))

(defn delete-keypairs-matching [re]
  (doseq [kp (filter #(re-find re (:keyName %)) (keypairs))]
    (delete-keypair (-> kp :keyName))))

(defn delete-unused-jclouds-keypairs
  []
  (let [keep (into #{} (map :keyName (instances)))]
    (doseq [k (->> (keypairs)
                   (filter #(re-find #"^jclouds" (:keyName %)))
                   (filter #(not (contains? keep (:keyName %)))))]
      (delete-keypair (:keyName k)))))