     )
   (:gen-class))
 
-(defn- sqs-client [] (apply sqs/create-client
-                            (vals (config :aws-credentials))))
+(defn- sqs-client [credentials] (apply sqs/create-client credentials))
 (defn- sqs-queue [client queue-name] (sqs/create-queue client queue-name))
 
 (defn- workspace-dir [basedir url]
   (join "/" [basedir (last (split url #"/")) "workspace"]))
 
-(defn process-push-message [client {payload :body}]
+(defn process-push-message [client workspaces-path {payload :body}]
   (when-let [url (payload/clone-target-url payload)]
     (let [repo (git/fresh-clone url
-                                (workspace-dir (config :workspaces-path) url)
+                                (workspace-dir workspaces-path url)
                                 "master")
           uuid (str (java.util.UUID/randomUUID))]
       (println "Iterating over jobs for" url)

         git-ref  :ref
         script   :script}  (read-body message)

        workspace-path      (join "/" [(config :workspaces-path)
                                       job-name
                                       "workspace"])

        existing-log        (io/get-key (config :log-key))

        repo                (git/fresh-clone git-url workspace-path git-ref)
        build               (runner/run! workspace-path script)

    (println "superset?" completed-job-names upstream-job-names)
    (doto (superset? completed-job-names upstream-job-names) println)))

(defn parser [config]
  (let [client (sqs-client (vals (config :aws-credentials)))
        q (sqs-queue client "cu-pushes")] ; TODO: use queue name from config
    (println "Starting parser")
    (dorun
      (map (sqs/deleting-consumer client
                                  (partial process-push-message
                                           client
                                           (config :workspaces-path)))
           (sqs/polling-receive client q
                                :max-wait (config :queue-max-wait)
                                :period (config :queue-period)
                                :limit 10)))))

(defn worker [config]
  (let [client (sqs-client (vals (config :aws-credentials)))
        q (sqs-queue client "cu-builds")]
    (println "Starting worker")
    (dorun
      (map (sqs/deleting-consumer client
                                  (runner/decide-whether-to
                                    run-job-from-message
                                    upstream-all-passed?))
           (filter no-pending-upstream-jobs?
                   (sqs/polling-receive client q
                                        :max-wait (config :queue-max-wait)
                                        :period (config :queue-period)
                                        :limit 10))))))

(defn -main [command & args]
  (case command

    "parser"
    (parser global-config/config)

    "worker"
    (worker global-config/config)

    nil))
