#lang imperative-syndicate

(provide (all-from-out "protocol.rkt")
         (all-from-out "client.rkt")
         (all-from-out "client/tcp.rkt")
         (all-from-out "client/loopback.rkt")
         (all-from-out "server.rkt")
         (all-from-out "server/tcp.rkt")
         (all-from-out "server/websocket.rkt"))

(require "protocol.rkt")

(require/activate "client.rkt")
(require/activate "client/tcp.rkt")
(require/activate "client/loopback.rkt")

(require/activate "server.rkt")
(require/activate "server/tcp.rkt")
(require/activate "server/websocket.rkt")

(module+ main
  (require racket/cmdline)
  (define tcp-port default-tcp-broker-port)
  (define http-port default-http-broker-port)
  (command-line #:once-any
                ["--tcp" port
                 ((format "Listen on plain TCP port (default ~a)" default-tcp-broker-port))
                 (set! tcp-port (string->number port))]
                ["--no-tcp" "Do not listen on any plain TCP port"
                 (set! tcp-port #f)]
                #:once-any
                ["--http" port
                 ((format "Listen on websocket HTTP port (default ~a)" default-http-broker-port))
                 (set! http-port (string->number port))]
                ["--no-http" "Do not listen on any websocket HTTP port"
                 (set! http-port #f)])
  (extend-ground-boot! (lambda ()
                         (when tcp-port (spawn-tcp-broker! tcp-port))
                         (when http-port (spawn-websocket-broker! http-port)))))

(define-logger syndicate/broker)

(when (log-level? syndicate/broker-logger 'debug)
  (spawn #:name 'server-debug
         (on (asserted (server-connection $id $scope))
             (log-syndicate/broker-debug "C+ ~v ~v" id scope))
         (on (retracted (server-connection $id $scope))
             (log-syndicate/broker-debug "C- ~v ~v" id scope))
         (on (message (server-inbound $id $p))
             (log-syndicate/broker-debug "CIN  ~v ~v" id p))
         (on (message (server-outbound $id $p))
             (log-syndicate/broker-debug "COUT ~v ~v" id p))))
