#!bin/picolisp lib.l
# 03feb16abu
# Use: bin/replica <port|num> <keyFile> <journal> <dbFile> <blob/app/> [dbs1 ..]
#    : bin/ssl <host> 443 '<port|name>/!replica' <keyFile> <journal> <blob/app/> 20 [60]

(load "@lib/misc.l" "@lib/http.l")

(allow "!replica")

(argv *Arg1 *KeyFile *Journal *Pool *Blob . *Dbs)

(unless (info *KeyFile)
   (bye) )

(setq
   *Arg1 (format *Arg1)
   *Port (or (format (sys "PORT")) *Arg1)
   *SSLKey (in *KeyFile (line T)) )

(de replica ()
   (when (= (line T) *SSLKey)
      (let? X (line T)
         (if (format X)
            (when (out (tmp 'replica) (echo @))    # Journal
               (protect
                  (prin (peek))
                  (flush)
                  (journal (tmp 'replica)) ) )
            (let Blob (pack *Blob X)               # Blob
               (call 'mkdir "-p" (dirname Blob))
               (and
                  (format (line T))
                  (out (tmp 'replica) (echo @))
                  (protect
                     (prin (peek))
                     (flush)
                     (call "mv" (tmp 'replica) Blob) ) ) ) ) ) ) )

(pool *Pool (mapcar format *Dbs) *Journal)

(retire *Arg1)

# Non-forking server
(setq *Port (port *Port))
(loop
   (http (setq *Sock (listen *Port)))
   (close *Sock) )
