 
 (def last-week (t/minus (.withTimeAtStartOfDay (l/local-now)) (t/weeks 1)))
 
-(defn- get-latest-synced-build-start []
+(defn- get-latest-synced-build-start [buildviz-url]
   (let [response (client/get (format "%s/status" buildviz-url))
         buildviz-status (j/parse-string (:body response) true)]
     (when-let [latest-build-start (:latestBuildStart buildviz-status)]
       (tc/from-long latest-build-start))))
 
-(defn- get-start-date [date-from-config]
+(defn- get-start-date [buildviz-url date-from-config]
   (if (some? date-from-config)
     date-from-config
-    (if-let [latest-sync-build-start (get-latest-synced-build-start)]
+    (if-let [latest-sync-build-start (get-latest-synced-build-start buildviz-url)]
       latest-sync-build-start
       last-week)))
 
 ;; run
 
-(defn- emit-start [sync-start-time pipeline-stages]
+(defn- emit-start [go-url buildviz-url sync-start-time pipeline-stages]
   (println "Go" go-url (distinct (map :group pipeline-stages)) "-> buildviz" buildviz-url)
   (print (format "Finding all pipeline runs for syncing (starting from %s)..."
                  (tf/unparse (:date-time tf/formatters) sync-start-time)))

  (println "done")
  pipeline-stages)

(defn -main [& c-args]
  (def args (parse-opts c-args cli-options))

  (when (or (:help (:options args))
            (empty? (:arguments args)))
    (println (usage (:summary args)))
    (System/exit 0))

  (def go-url (first (:arguments args)))
  (def buildviz-url (:buildviz-url (:options args)))

  (let [sync-start-time (get-start-date (:sync-start-time (:options args)))
        sync-jobs-for-pipelines (set (:sync-jobs-for-pipelines (:options args)))
        selected-pipeline-group-names (set (:pipeline-groups (:options args)))]

    (->> (goapi/get-stages go-url)
         (select-stages selected-pipeline-group-names)
         (emit-start sync-start-time)
         (mapcat #(stage-instances-from sync-start-time %))
         (sort-by :scheduled-time)
         (take-while :finished)
         (emit-sync-start)
         (progress/init "Syncing")
         (map add-inputs-for-stage-instance)
         (map add-job-instances-for-stage-instance)
         (map #(aggregate-jobs-for-stage-instance % sync-jobs-for-pipelines))
         (mapcat stage-instances->builds)
         (map put-to-buildviz)
         (map progress/tick)
         dorun
         (progress/done))))

   :scheduled-time (tc/from-long (apply min (map :scheduled_date jobs)))
   :job-names (map :name jobs)})

(defn stage-instances-from [go-url sync-start-time {stage-name :stage pipeline-name :pipeline}]
  (let [safe-build-start-date (t/minus sync-start-time (t/millis 1))]
    (->> (goapi/get-stage-history go-url pipeline-name stage-name)
         (map parse-stage-instance)
