#!/bin/sh
# pic remote install and uninstall: a login agent so pic remote comes back after a login with no
# one there. launchd, systemd --user and cron are each driven through stand-ins (PIC_TEST_AGENT
# names the mechanism and a directory of fake launchctl, systemctl and crontab that log what they
# were asked), so no test touches the real ones; without the seam, a test's HOME is refused before
# anything runs. The store must open with no one there (a key in the keychain or the key file),
# and pic remote --login, which the agent runs, waits for a pairing and leaves quietly when one
# already runs or the store asks for a passphrase.
# Usage: test/pic/remote-agent.sh [--no-faults] (the release build: no deadline seam to test)
set -eu
PIC=${PIC:?set PIC to the pic binary}
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-agent.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic" "$T/bin"
unset PIC_KEY_FD PIC_TEST_PASSPHRASE PIC_TEST_AGENT PIC_TEST_KEYCHAIN
pids=
cleanup() {
    exec 2> /dev/null
    for p in $pids; do kill -9 "$p" 2> /dev/null || true; done
    rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
# and a pic remote this run starts ends by itself (dev builds) should the run be killed before cleanup
export PIC_TEST_RC_DEADLINE_S=1800
fail() {
    printf 'FAIL: %s\n' "$*" >&2
    for f in "$T"/*.out "$T"/*.err "$T/calls"; do [ -s "$f" ] && { printf -- '--- %s\n' "$f" >&2; tail -20 "$f" >&2; }; done
    exit 1
}
await() { # FILE PATTERN: the fixed string in FILE within 30 s
    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
}
run() { # NAME ARGS...: pic with ARGS, its output in $T/NAME.out and .err, its status in rc
    n=$1
    shift
    rc=0
    "$PIC" "$@" > "$T/$n.out" 2> "$T/$n.err" < /dev/null || rc=$?
}

# The stand-ins: each logs its arguments, one call a line. crontab keeps the table in $T/crontab.
for prog in launchctl systemctl; do
    printf '#!/bin/sh\necho "%s $*" >> "%s/calls"\n' "$prog" "$T" > "$T/bin/$prog"
done
cat > "$T/bin/crontab" <<EOF
#!/bin/sh
echo "crontab \$*" >> "$T/calls"
if [ "\$1" = -l ]; then
    [ -f "$T/crontab" ] || { echo "crontab: no crontab for you" >&2; exit 1; }
    cat "$T/crontab"
else
    cp "\$1" "$T/crontab"
fi
EOF
chmod +x "$T/bin/launchctl" "$T/bin/systemctl" "$T/bin/crontab"

# No store yet: nothing to start at login.
run nostore remote install
[ "$rc" = 1 ] || fail "no store: exit $rc"
grep -qF 'pair a phone' "$T/nostore.err" || fail "no store: $(cat "$T/nostore.err")"
[ -e "$HOME/Library" ] && fail "no store: wrote under Library"
printf 'PASS: pic remote install with no store says to pair first and writes nothing\n'

# A store whose key asks for a passphrase: no one can type it at login.
printf 'agent-test-pass\n' > "$T/pass"
"$PIC" --passphrase-fd 3 auth rekey passphrase 3< "$T/pass" > /dev/null 2> "$T/rekey.err" < /dev/null || fail "rekey passphrase: $(cat "$T/rekey.err")"
export PIC_TEST_AGENT="launchd:$T/bin" # (an assignment before a function call may outlive it)
run phrase remote install
[ "$rc" = 1 ] || fail "passphrase: exit $rc"
grep -qF 'pic auth rekey' "$T/phrase.err" || fail "passphrase: $(cat "$T/phrase.err")"
[ -e "$T/calls" ] && fail "passphrase: ran $(cat "$T/calls")"
run phrasefd --passphrase-fd 3 remote install 3< "$T/pass"
[ "$rc" = 1 ] || fail "passphrase on a descriptor: exit $rc"
grep -qF 'pic auth rekey' "$T/phrasefd.err" || fail "passphrase on a descriptor: $(cat "$T/phrasefd.err")"
unset PIC_TEST_AGENT
run login remote --login
[ "$rc" = 0 ] || fail "--login with a passphrase store: exit $rc"
grep -qF 'pic auth rekey' "$T/login.err" || fail "--login with a passphrase store: $(cat "$T/login.err")"
printf 'PASS: a store that asks for a passphrase is refused, and pic remote --login leaves quietly\n'

# The key in the key file: the store opens with no one there.
"$PIC" --passphrase-fd 3 auth rekey file 3< "$T/pass" > /dev/null 2> "$T/rekey.err" < /dev/null || fail "rekey file: $(cat "$T/rekey.err")"
# A test's HOME is not the account's: without the seam nothing is installed and nothing runs.
run notmine remote install
[ "$rc" = 1 ] || fail "not my home: exit $rc"
grep -qF 'home directory' "$T/notmine.err" || fail "not my home: $(cat "$T/notmine.err")"
[ -e "$HOME/Library" ] || [ -e "$HOME/.config" ] && fail "not my home: wrote a file"
printf 'PASS: without the stand-ins a test HOME is refused before anything runs\n'

# launchd: a LaunchAgent for pic remote --login, booted out and in again; status says so. A key in
# this shell's environment alone is named, with the command that stores it, until it is stored.
export PIC_TEST_AGENT="launchd:$T/bin" OPENROUTER_API_KEY=agent-test-key
PL="$HOME/Library/LaunchAgents/app.zeitforge.pic.remote.plist"
run ld1 remote install
[ "$rc" = 0 ] || fail "launchd: exit $rc: $(cat "$T/ld1.err")"
[ -f "$PL" ] || fail "launchd: no plist"
for want in "<string>$PIC</string>" '<string>remote</string>' '<string>--login</string>' '<key>RunAtLoad</key>' \
    '<key>SuccessfulExit</key>' "<string>$HOME/.pic/remote.log</string>" '<string>app.zeitforge.pic.remote</string>'; do
    grep -qF -- "$want" "$PL" || fail "launchd: plist lacks $want: $(cat "$PL")"
done
if command -v plutil > /dev/null 2>&1; then plutil -lint "$PL" > /dev/null || fail "launchd: plist does not parse"; fi
U=$(id -u)
grep -qxF "launchctl bootstrap gui/$U $PL" "$T/calls" || fail "launchd: calls: $(cat "$T/calls")"
grep -qF 'whenever you log in' "$T/ld1.out" || fail "launchd: says: $(cat "$T/ld1.out")"
SHELLONLY='OPENROUTER_API_KEY (openrouter) is set in this shell only: pic remote started at login will not see it. pic auth import OPENROUTER_API_KEY stores it for pic remote.'
grep -qxF "$SHELLONLY" "$T/ld1.out" || fail "launchd: the shell-only key: $(cat "$T/ld1.out")"
run st1 remote status
grep -qF 'starts at login (launchd)' "$T/st1.out" || fail "launchd: status: $(cat "$T/st1.out")"
grep -qxF "$SHELLONLY" "$T/st1.out" || fail "launchd: status: the shell-only key: $(cat "$T/st1.out")"
"$PIC" auth import OPENROUTER_API_KEY > /dev/null 2> "$T/import.err" < /dev/null || fail "import: $(cat "$T/import.err")"
run st1b remote status
grep -qF 'OPENROUTER_API_KEY' "$T/st1b.out" && fail "launchd: status after import: $(cat "$T/st1b.out")"
run st1j remote status --json
grep -qF '"loginAgent":"launchd"' "$T/st1j.out" || fail "launchd: status --json: $(cat "$T/st1j.out")"
run ld2 remote install
[ "$rc" = 0 ] || fail "launchd: again: exit $rc"
grep -qxF "launchctl bootout gui/$U/app.zeitforge.pic.remote" "$T/calls" || fail "launchd: again: $(cat "$T/calls")"
[ "$(ls "$HOME/Library/LaunchAgents")" = app.zeitforge.pic.remote.plist ] || fail "launchd: again: $(ls "$HOME/Library/LaunchAgents")"
: > "$T/calls"
run lu1 remote uninstall
[ "$rc" = 0 ] || fail "launchd: uninstall: exit $rc"
[ -e "$PL" ] && fail "launchd: uninstall left the plist"
grep -qxF "launchctl bootout gui/$U/app.zeitforge.pic.remote" "$T/calls" || fail "launchd: uninstall: $(cat "$T/calls")"
run st2j remote status --json
grep -qF '"loginAgent":""' "$T/st2j.out" || fail "launchd: status after: $(cat "$T/st2j.out")"
run lu2 remote uninstall
[ "$rc" = 0 ] || fail "launchd: uninstall again: exit $rc"
grep -qF 'was not' "$T/lu2.out" || fail "launchd: uninstall again: $(cat "$T/lu2.out")"
printf 'PASS: launchd: install writes and boots a LaunchAgent, status names it and a key only this shell has, uninstall boots it out\n'

# systemd --user: a unit enabled and started now; uninstall disables and stops it.
export PIC_TEST_AGENT="systemd:$T/bin"
UN="$HOME/.config/systemd/user/pic-remote.service"
: > "$T/calls"
run sd1 remote install
[ "$rc" = 0 ] || fail "systemd: exit $rc: $(cat "$T/sd1.err")"
grep -qxF "ExecStart=\"$PIC\" \"remote\" \"--login\"" "$UN" || fail "systemd: unit: $(cat "$UN")"
grep -qxF 'Restart=on-failure' "$UN" && grep -qxF 'WantedBy=default.target' "$UN" || fail "systemd: unit: $(cat "$UN")"
grep -qxF "StandardOutput=append:$HOME/.pic/remote.log" "$UN" || fail "systemd: unit log: $(cat "$UN")"
grep -qxF 'systemctl --user daemon-reload' "$T/calls" && grep -qxF 'systemctl --user enable --now pic-remote.service' "$T/calls" ||
    fail "systemd: calls: $(cat "$T/calls")"
run st3 remote status
grep -qF 'starts at login (systemd)' "$T/st3.out" || fail "systemd: status: $(cat "$T/st3.out")"
run su1 remote uninstall
[ "$rc" = 0 ] && [ ! -e "$UN" ] || fail "systemd: uninstall: exit $rc"
grep -qxF 'systemctl --user disable --now pic-remote.service' "$T/calls" || fail "systemd: uninstall: $(cat "$T/calls")"
printf 'PASS: systemd: install enables and starts a user unit, uninstall disables and stops it\n'

# cron elsewhere: an @reboot line of its own beside the user's lines, never twice; uninstall takes
# only that line.
export PIC_TEST_AGENT="cron:$T/bin"
printf '0 3 * * * /usr/bin/true # mine\n' > "$T/crontab"
run cr1 remote install
[ "$rc" = 0 ] || fail "cron: exit $rc: $(cat "$T/cr1.err")"
run cr2 remote install
[ "$(grep -c 'pic remote install' "$T/crontab")" = 1 ] || fail "cron: table: $(cat "$T/crontab")"
grep -qF "@reboot '$PIC' 'remote' '--login' >> '$HOME/.pic/remote.log' 2>&1" "$T/crontab" || fail "cron: line: $(cat "$T/crontab")"
grep -qxF '0 3 * * * /usr/bin/true # mine' "$T/crontab" || fail "cron: the user's line: $(cat "$T/crontab")"
grep -qF 'pic remote' "$T/cr1.out" || fail "cron: says: $(cat "$T/cr1.out")"
run st4j remote status --json
grep -qF '"loginAgent":"cron"' "$T/st4j.out" || fail "cron: status: $(cat "$T/st4j.out")"
run cu1 remote uninstall
[ "$rc" = 0 ] || fail "cron: uninstall: exit $rc"
[ "$(cat "$T/crontab")" = '0 3 * * * /usr/bin/true # mine' ] || fail "cron: uninstall: $(cat "$T/crontab")"
printf 'PASS: cron: one @reboot line beside the user'"'"'s, never twice; uninstall takes only it\n'
unset PIC_TEST_AGENT

# What the agent runs: pic remote --login with no phone paired yet waits for one (holding the
# lock), a second --login leaves quietly, a plain pic remote says one is running, and stop ends it.
"$PIC" remote --login > "$T/wait.out" 2> "$T/wait.err" < /dev/null &
WP=$!
pids="$pids $WP"
await "$T/wait.out" 'waiting'
run again remote --login
[ "$rc" = 0 ] || fail "--login while one runs: exit $rc"
grep -qF 'already running' "$T/again.err" || fail "--login while one runs: $(cat "$T/again.err")"
run plain remote
[ "$rc" = 1 ] || fail "pic remote while one runs: exit $rc"
run st5 remote status
grep -qF 'waiting for a phone' "$T/st5.out" || fail "--login: status: $(cat "$T/st5.out")"
run stop remote stop
[ "$rc" = 0 ] || fail "stop: exit $rc: $(cat "$T/stop.err")"
rc=0
wait "$WP" || rc=$?
[ "$rc" = 0 ] || fail "--login: stopped with exit $rc"
printf 'PASS: pic remote --login waits for a pairing, leaves quietly beside a running one, and stops\n'

# A test killed before its cleanup cannot leave a pic remote behind: with the tests' deadline it
# ends by itself (dev builds; a release build has no seam).
if [ "${1:-}" != --no-faults ]; then
    PIC_TEST_RC_DEADLINE_S=2 "$PIC" remote --login > "$T/dl.out" 2> "$T/dl.err" < /dev/null &
    WP=$!
    pids="$pids $WP"
    await "$T/dl.out" 'waiting'
    i=0
    while kill -0 "$WP" 2> /dev/null; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "deadline: pic remote still runs"; sleep 0.05; done
    printf 'PASS: a pic remote started by a test ends by itself at the tests'"'"' deadline\n'
fi
