#!/bin/sh
# Remote control through a relay (docs/design/remote-protocol.md): pic remote pair and pic remote
# against the test relay (test/pic/fake_relay.c, section 6 with the deployed Worker's deviations)
# and a scripted phone (test/pic/fake_phone.c, the initiator on pic's own Noise module). Pairing:
# the happy path, a wrong secret, a no, an expired offer, an offer used twice, and the phone that
# was not reading when paired was posted. Sessions: an unknown key, the wrong channel, a replayed
# and a reordered record, reconnecting and catching up from a cursor, a steer, an idle prompt, an
# abort, unpairing at the terminal and from the phone, pic remote killed at any moment, and two
# phones at once. Usage: test/pic/remote.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}
SQLITE3=${SQLITE3:-sqlite3}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-remote.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic"
unset PIC_KEY_FD
export ANTHROPIC_API_KEY=pic-remote-test-key PIC_PI_EXPORT=0
pids=
cleanup() {
    for p in $pids; do kill -9 "$p" 2>/dev/null || true; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() {
    printf 'FAIL: %s\n' "$*" >&2
    for f in "$T"/*.out "$T"/*.err; do [ -s "$f" ] && { printf -- '--- %s\n' "$f" >&2; tail -20 "$f" >&2; }; done
    exit 1
}
bg() { pids="$pids $1"; }
await() { # FILE PATTERN [TRIES]: wait for the fixed string PATTERN in FILE (50 ms a try, 30 s by default)
    i=0
    until grep -qF -- "$2" "$1" 2>/dev/null; do
        i=$((i + 1))
        [ "$i" -lt "${3:-600}" ] || fail "timed out waiting for $2 in $1"
        sleep 0.05
    done
}
gone() { # PID: wait up to 30 s for it to exit; its status in rc
    rc=0
    wait "$1" || rc=$?
}
uq() { "$SQLITE3" "$HOME/.pic/pic.sqlite" "$1"; }

if [ "$FAULTS" = 0 ]; then
    # The release build reads the passphrase only from a terminal: without one, pic remote says so
    # and pairs nothing. The rest needs PIC_TEST_PASSPHRASE, a dev build's seam.
    if "$PIC" remote < /dev/null > "$T/notty.out" 2> "$T/notty.err"; then fail "release: pic remote ran with no terminal"; fi
    [ -s "$T/notty.err" ] || fail "release: no message"
    printf 'PASS: release: pic remote without a terminal exits with a message\n'
    exit 0
fi
export PIC_TEST_PASSPHRASE=remote-test-pass

# One relay for the whole run; its deadline outlives the script.
"$RELAY" "$T/relay.port" 600 test-invite > "$T/relay.out" 2> "$T/relay.err" &
bg $!
i=0
while [ ! -s "$T/relay.port" ]; do
    i=$((i + 1))
    [ "$i" -lt 600 ] || fail "relay did not start"
    sleep 0.05
done
BASE="http://127.0.0.1:$(cat "$T/relay.port")"
"$PIC" settings remote.relay "$BASE" > /dev/null
state() { curl -s -X POST "$BASE/_test/state"; }
ctl() { curl -s -X POST "$BASE/_test/$1" > /dev/null; }

np=0
offer() { # start pic remote pair --pipe; its output in $PO, its stdin the fifo $PI (fd 3)
    np=$((np + 1))
    PO="$T/pair$np.out"
    PI="$T/pair$np.in"
    mkfifo "$PI"
    "$PIC" remote pair --pipe < "$PI" > "$PO" 2> "$T/pair$np.err" &
    PP=$!
    bg $PP
    exec 3> "$PI"
    await "$PO" '"type":"offer"'
    URL=$(sed -n 's/.*"url":"\([^"]*\)".*/\1/p' "$PO" | head -1)
    [ -n "$URL" ] || fail "offer: no address in $(cat "$PO")"
}
phone_pair() { # DIR NAME [ARGS]: the phone pairs in the background; its output in DIR.out
    mkdir -p "$1"
    "$PHONE" "$1" pair "$URL" "$2" ${3:-} > "$1.out" 2>&1 &
    PH=$!
    bg $PH
}

# ---- pairing -------------------------------------------------------------------------------
# Without the invite the relay refuses a new mailbox (403), and pairing says which setting to set.
if "$PIC" remote pair --pipe < /dev/null > "$T/noinv.out" 2> "$T/noinv.err"; then fail "invite: paired without one"; fi
grep -qF 'remote.invite' "$T/noinv.err" || fail "invite: message: $(cat "$T/noinv.err")"
"$PIC" settings remote.invite test-invite > /dev/null
printf 'PASS: a relay that wants an invite: pairing names the setting\n'

# The happy path: the two codes match, a yes commits one sealed device row, the phone hears paired,
# and the pairing channel is gone at the relay afterwards.
offer
case "$URL" in "$BASE/#p1."*) ;; *) fail "offer: address $URL" ;; esac
phone_pair "$T/ph1" "Phone One"
await "$PO" '"type":"code"'
await "$T/ph1.out" 'code '
want=$(sed -n 's/^code //p' "$T/ph1.out")
grep -qF "\"code\":\"$want\"" "$PO" || fail "pair: the codes differ: $(cat "$PO") / $want"
grep -qF '"name":"Phone One"' "$PO" || fail "pair: name: $(cat "$PO")"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 0 ] || fail "pair: a row before the yes"
echo y >&3
gone $PH
[ "$rc" = 0 ] || fail "pair: phone exit $rc"
grep -qx paired "$T/ph1.out" || fail "pair: phone: $(cat "$T/ph1.out")"
gone $PP
exec 3>&-
[ "$rc" = 0 ] || fail "pair: pic exit $rc"
[ "$(uq 'SELECT count(*) FROM picu_remote_device')" = 1 ] || fail "pair: rows"
[ "$(uq 'SELECT count(*) FROM picu_remote_key')" = 3 ] || fail "pair: keys"
uq "SELECT sealed FROM picu_remote_device" | grep -qF 'Phone One' && fail "pair: the device row is not sealed"
state | grep -qF 'channels 1 ' || fail "pair: relay channels: $(state)"
"$PIC" remote devices > "$T/devices.out" || fail "devices"
grep -qF 'Phone One' "$T/devices.out" || fail "devices: $(cat "$T/devices.out")"
grep -qF 'not running' "$T/devices.out" || fail "devices: running: $(cat "$T/devices.out")"
printf 'PASS: pairing: matching codes, a yes, one sealed row, the pairing channel deleted\n'
