 (defn set-logging-level [logger-name level]
   (.setLevel (java.util.logging.Logger/getLogger logger-name) level))
 
-;; For now, this impl simply returns the first service as soon as it is discovered
-(defn discover-ambly-webdav-bonjour-services
-  "Looks for Ambly WebDAV services advertised via Bonjour."
-  [timeout]
+(defn service-name->display-name [service-name]
+  (subs service-name (count "Ambly WebDAV Server on ")))
+
+(defn service-map->choice-list [service-map]
+  (map vector (iterate inc 1) service-map))
+
+(defn print-services [service-map]
+  (doseq [[choice-number [service-name _]] (service-map->choice-list service-map)]
+    (println (str "[" choice-number "] " (service-name->display-name service-name)))))
+
+(defn discover-and-pick-ambly-instance
+  "Looks for Ambly WebDAV services advertised via Bonjour and presents
+  a simple command-line UI letting user pick one."
+  []
   (let [reg-type "_http._tcp.local."
-        ;discovered-services (atom {})
-        discovered-services (promise)
+        discovered-services (atom (sorted-map))
         mdns-service (JmDNS/create)
         service-listener
         (reify ServiceListener

              (when (.startsWith name "Ambly WebDAV Server")
                (.requestServiceInfo mdns-service (.getType service-event) (.getName service-event) 1))))
          (serviceRemoved [_ service-event]
            #_(swap! discovered-services dissoc (.getName service-event)))
          (serviceResolved [_ service-event]
            (let [entry {(.getName service-event)
                         (let [info (.getInfo service-event)]
                           {:address (.getAddress info)
                            :port    (.getPort info)})}]
              #_(swap! discovered-services merge entry)
              (deliver discovered-services entry))))]
    (try
      (.addServiceListener mdns-service reg-type service-listener)
      #_(Thread/sleep timeout)
      (deref discovered-services timeout {})
      (finally
        (.removeServiceListener mdns-service reg-type service-listener)
        (.close mdns-service)))))

(defn socket [host port]
  (let [socket (Socket. host port)

(defn setup
  [repl-env opts]
  (let [_ (set-logging-level "javax.jmdns" java.util.logging.Level/SEVERE)
        [webdav-endpoint-name webdav-endpoint] (discover-and-pick-ambly-instance)
        _ (println "\nConnecting to" (service-name->display-name webdav-endpoint-name) "...\n")
        ; Assuming IPv4 for now
        endpoint-address (.getHostAddress (:address webdav-endpoint))
        endpoint-port (:port webdav-endpoint)
