#lang imperative-syndicate

(require/activate imperative-syndicate/drivers/external-event)
(require/activate imperative-syndicate/drivers/filesystem)
(require racket/file)

(require (only-in racket/port read-bytes-line-evt))
(require (only-in racket/string string-trim string-split))

(spawn #:name 'monitor-shell
       (define e (read-bytes-line-evt (current-input-port) 'any))
       (on (message (inbound (external-event e (list $line))))
           (match line
             [(? eof-object?)
              (stop-current-facet (send! (list "close" 'all)))]
             [(? bytes? command-bytes)
              (send! (string-split (string-trim (bytes->string/utf-8 command-bytes))))])))

(spawn #:name 'monitor-opener

       (define (monitor name reader-proc)
         (spawn #:name (list 'monitor name)
                (stop-when (message (list "close" 'all))) ;; old-syndicate version used wildcard
                (stop-when (message (list "close" name)))
                (on (asserted (file-content name reader-proc $data))
                    (log-info "~a: ~v" name data))))

       (on (message (list "open" $name)) (monitor name file->bytes))

       ;; The driver can track directory "contents" just as well as files.
       (on (message (list "opendir" $name)) (monitor name directory-list)))
