#!/bin/sh
# /rc (/remote-control) in the terminal interface, against the test relay (test/pic/fake_relay.c)
# and a scripted phone (test/pic/fake_phone.c). With no phone paired, /rc goes straight to pairing:
# the pairing QR code, nothing of ssh, and the invite setting named only when pairing needs it.
# With a phone paired, /rc turns pic remote on and shows the phone page's address for this
# conversation and its QR code, and the footer says "remote on". /rc ssh and pic rc --ssh are the
# ssh path, as text. pic rc prints the phone's address.
# Usage: test/tui/rc.sh [--no-faults]
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
RELAY=${RELAY:?set RELAY to the fake_relay binary}
PHONE=${PHONE:?set PHONE to the fake_phone binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
FAULTS=yes # --no-faults (the release build): the ssh lookups and the paired cases need the dev build's seams
[ "${1:-}" = --no-faults ] && FAULTS=no
S=$(cd "$(dirname "$0")/../pic/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-rc.XXXXXX")
export HOME="$T/home"
mkdir -p "$HOME/.pic" "$T/ws" "$T/slog"
export ANTHROPIC_API_KEY=pic-rc-test-key PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0
export PIC_NO_NATIVE_CLIPBOARD=1 # never the real clipboard
export FAKE_RELAY_BEAT_MS=60000 # a quiet relay: connected must not wait for its first comment
unset PIC_TEST_PASSPHRASE PIC_KEY_FD PIC_TEST_KEYCHAIN # a test's HOME: the store's key is a file there, no passphrase
pids=
cleanup() {
    exec 2> /dev/null
    "$PIC" remote stop > /dev/null 2>&1 || :
    for p in $pids; do kill -9 "$p" 2> /dev/null || :; done
    [ -n "${KEEP:-}" ] || rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() {
    printf 'FAIL: %s\n' "$*" >&2
    [ -s "$HOME/.pic/remote.log" ] && tail -20 "$HOME/.pic/remote.log" >&2
    exit 1
}
plain() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\e\][^\a\e]*(\a|\e\\)//g; s/\r//g' "$1"; }
await() { # FILE PATTERN: wait up to 30 s for the fixed string PATTERN in FILE
    i=0
    until grep -qF -- "$2" "$1" 2> /dev/null; do
        i=$((i + 1))
        [ "$i" -lt 600 ] || fail "timed out waiting for $2 in $1"
        sleep 0.05
    done
}

"$RELAY" "$T/relay.port" 300 test-invite > "$T/relay.out" 2> "$T/relay.err" &
pids="$pids $!"
"$SERVER" "$T/sport" "$T/slog" 300 "sse:$S/text.sse" &
pids="$pids $!"
i=0
while [ ! -s "$T/relay.port" ] || [ ! -s "$T/sport" ]; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || fail "relay or model server did not start"
    sleep 0.05
done
BASE="http://127.0.0.1:$(cat "$T/relay.port")"
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m","contextWindow":200000}]}}}' \
    "$(cat "$T/sport")" > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
pic() { "$PIC" --db "$T/j.sqlite" --workspace "$T/ws" --model fake/m "$@"; }
drive() { # NAME COLS ROWS [pic args]: the terminal interface on the script on stdin
    name=$1 cols=$2 rows=$3
    shift 3
    "$DRIVE" "$T/$name.tx" "$cols" "$rows" "$PIC" --tui-mode regular --db "$T/j.sqlite" --workspace "$T/ws" --model fake/m "$@" ||
        fail "$name: $(plain "$T/$name.tx" | grep -v '^\s*$' | tail -12)"
}
"$PIC" settings remote.relay "$BASE" > /dev/null

# A conversation to open on the phone.
pic ask 'first question' > /dev/null 2> "$T/ask.err" || fail "ask: $(cat "$T/ask.err")"

# ---- ssh, as text: /rc ssh and pic rc --ssh -----------------------------------------------------
[ "$FAULTS" = yes ] && export PIC_TEST_RC="-|testmac.local|0"
pic rc --ssh > "$T/ssh.out" || fail "pic rc --ssh: exit $?"
grep -qF 'ssh -t ' "$T/ssh.out" || fail "pic rc --ssh: no command: $(cat "$T/ssh.out")"
grep -qF 'Remote Login' "$T/ssh.out" || fail "pic rc --ssh: no checks: $(cat "$T/ssh.out")"
! grep -qF -e '▀' -e '▄' -e '█' "$T/ssh.out" || fail "pic rc --ssh: a QR code"
drive ssh 100 40 <<'EOF2'
expect pic fake/m
send /rc ssh\r
expect Remote control over ssh
expect then run: cd
expect Remote Login
send c
expect Copied the command
send \e
wait 300
send \x04\x04
EOF2
grep -aq "$(printf '\033]52;c;')" "$T/ssh.tx" || fail "/rc ssh: c copied nothing"
! grep -q '▀' "$T/ssh.tx" || fail "/rc ssh: a QR code drawn"
unset PIC_TEST_RC
printf 'PASS: /rc ssh and pic rc --ssh: the ssh command and checks as text, no QR code; c copies\n'

# ---- no phone paired: /rc is pairing ------------------------------------------------------------
pic rc > "$T/none.out" || fail "pic rc unpaired: exit $?"
grep -qF 'No phone is paired' "$T/none.out" || fail "pic rc unpaired: $(cat "$T/none.out")"
if pic rc --link > /dev/null 2>&1; then fail "pic rc --link: a link with no phone paired"; fi
# Without the relay's invite, pairing cannot start: then, and only then, the setting is named.
drive noinvite 100 40 <<EOF2
expect pic fake/m
send /rc\r
expect remote.invite
send \e
wait 300
send \x04\x04
EOF2
"$PIC" settings remote.invite test-invite > /dev/null
drive pairing 100 50 <<EOF2
expect pic fake/m
send /rc\r
expect Scan this with your phone's camera to pair it
expect /#p1.
expect add the page to the Home Screen
send \e
wait 500
send /hotkeys\r
expect Other:
send \x04\x04
EOF2
plain "$T/pairing.tx" > "$T/pairing.txt"
grep -q '▀' "$T/pairing.tx" || fail "pairing: no QR code drawn"
! grep -qE 'ssh://|Remote Login|Tailscale' "$T/pairing.txt" || fail "pairing: ssh on the pairing screen"
! grep -qF 'remote.invite' "$T/pairing.txt" || fail "pairing: the invite named though it is set"
printf 'PASS: /rc with no phone paired goes straight to pairing: a QR code, no ssh; Esc closes\n'
printf 'PASS: /rc names remote.invite only when pairing cannot start without it\n'

if [ "$FAULTS" = no ]; then
    exit 0
fi

# ---- a phone paired: /rc turns remote on and shows this conversation's link ---------------------
mkfifo "$T/pair.in"
"$PIC" remote pair --pipe < "$T/pair.in" > "$T/pair.out" 2> "$T/pair.err" &
PP=$!
pids="$pids $PP"
exec 3> "$T/pair.in"
await "$T/pair.out" '"type":"offer"'
URL=$(sed -n 's/.*"url":"\([^"]*\)".*/\1/p' "$T/pair.out" | head -1)
mkdir -p "$T/ph"
"$PHONE" "$T/ph" pair "$URL" "Test Phone" > "$T/ph.out" 2>&1 &
pids="$pids $!"
await "$T/pair.out" '"type":"code"'
echo y >&3
await "$T/ph.out" paired
wait "$PP" || fail "pair: $(cat "$T/pair.out" "$T/pair.err")"
exec 3>&-
SID=$("${SQLITE3:-sqlite3}" "$T/j.sqlite" "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
LINK=$(pic rc --link) || fail "pic rc --link: exit $?"
case "$LINK" in "$BASE/#s="*"/$SID&c="*) ;; *) fail "pic rc --link: $LINK (session $SID)" ;; esac
pic rc > "$T/paired.out"
grep -qF "$LINK" "$T/paired.out" || fail "pic rc: no link: $(cat "$T/paired.out")"
grep -qF -e '▀' -e '▄' -e '█' "$T/paired.out" || fail "pic rc: no QR code"
grep -qF 'pic remote is not running' "$T/paired.out" || fail "pic rc: running: $(cat "$T/paired.out")"
printf 'PASS: pic rc prints the phone page address for the conversation and its QR code\n'

drive paired 120 50 -c <<EOF2
expect pic fake/m
send /rc\r
expect ● Remote control is on
expect Open this conversation on your phone
expect /#s=
expect Test Phone
expect ssh instead: /rc ssh
send c
expect Copied the link
send \r
wait 300
expect remote on
send \x04\x04
EOF2
plain "$T/paired.tx" > "$T/paired.txt"
grep -q '▀' "$T/paired.tx" || fail "paired: no QR code drawn"
! grep -qE 'ssh://|Remote Login|then run:' "$T/paired.txt" || fail "paired: ssh on the screen"
! grep -qF 'Run pic remote' "$T/paired.txt" || fail "paired: tells to run pic remote while it runs"
"$PIC" remote status > "$T/status.out"
grep -qF 'connected to' "$T/status.out" || fail "status: $(cat "$T/status.out")"
printf 'PASS: /rc with a phone paired: remote on and connected at once, the link and its QR code, no ssh\n'
printf 'PASS: the footer says remote on while pic remote is connected\n'

# Again, with remote on: s turns it off, and the footer marker goes.
drive off 120 50 -c <<'EOF2'
expect pic fake/m
send /rc\r
expect ● Remote control is on
send s
expect Remote control is off
send \e
wait 300
send \x04\x04
EOF2
"$PIC" remote status > "$T/status2.out"
grep -qF 'not running' "$T/status2.out" || fail "s: $(cat "$T/status2.out")"
printf 'PASS: s on /rc turns remote control off\n'
