#!/usr/bin/pil
# 05jul24abu
# Pseudo Terminal (PilBox)
# pty [host] [flg]

(load "@lib/term.l")

(setq
   *Host (or (opt) "localhost")
   *Port 8081 )  # Sync with ~/Port in PilBox

(unless (setq *Sock (connect *Host (inc *Port)))
   (bye) )

(out *Sock
   (in "~/.pty" (echo))  # Sync with ~/.pty in PilBox
   (prinl) )
(in *Sock (rd 2))  # Skip "\r\n"

(finish (prinl))

(de sendCmd @
   (udp *Host `(inc *Port)
      (cons (in "~/.pty" (line T)) (rest)) ) )

(unless (opt)
   (task (port (+ *Port 2))
      (let? S (accept @)
         (catch '(NIL)
            (in S
               (when (= (rd) (in "~/.pty" (line T)))
                  (let Z (tmp "pty.zip")
                     (casq (rd)
                        (+
                           (apply call (rd) "zip" "-r" Z)
                           (in Z (out S (echo))) )
                        (-
                           (out Z (echo))
                           (call "unzip" "-o" Z) ) ) ) ) )
            (off *Msg) )
         (close S)
         (and *Msg (prinl @)) ) ) )

(when (getTerm)
   (sendCmd
      (cons 'setTerm (sys "TERM") @)
      '(off *Err) )
   (de *Winch
      (sendCmd (cons 'setTerm (sys "TERM") (getTerm))) ) )

(raw T)
(call "stty" "intr" NIL)

(task *Sock
   (in @
      (ifn (rd 1)
         (bye)
         (wr @)
         (flush) ) ) )

(loop
   (and (key) (out *Sock (prin @))) )
