#!/usr/bin/env bash
# deploy-souveraine.sh — ship a cross-built Souveraine to the Pixel 3.
#
# The binary is cross-compiled on this box by the souveraine repo's
# scripts/build-cross.sh (target/aarch64-unknown-linux-gnu/release/souveraine,
# linked against the /usr/aarch64-linux-gnu sysroot). This script ships that
# binary + the systemd user unit — no on-device build, no makepkg, no phone
# RAM pressure. Binary lands in /usr/local/bin (pacman's /usr/bin is reserved
# for packaged software; this isn't a pacman package). Redeploy = rerun.
#
# Data: mirrors ~/.souveraine (agents, memfs, tokens, db).
# Identity: private keys are EXCLUDED by default. The phone retains or creates
# its own machine key and per-agent keys. This is safe for a new device, but it
# is not yet the planned commissioned-node flow: a separate agent key cannot
# prove it is an authorized fork of an existing agent. --clone-identity is an
# explicit, same-instance migration escape hatch; it copies private keys and
# must never be used as federation enrolment.
set -euo pipefail

SSH=(ssh -F /dev/null -i "$HOME/.ssh/ani" -o BatchMode=yes -o ConnectTimeout=5)
SCP=(scp -F /dev/null -i "$HOME/.ssh/ani" -o BatchMode=yes)
USB_IP=172.16.42.1
WIFI_IP=10.10.20.154
SRC="$HOME/Projects/souveraine"
UNIT="$SRC/packaging/souveraine.service"
BIN="$SRC/target/aarch64-unknown-linux-gnu/release/souveraine"

clone_identity=0
case "${1:-}" in
    "") ;;
    --clone-identity) clone_identity=1 ;;
    *)
        echo "usage: $0 [--clone-identity]" >&2
        exit 2
        ;;
esac

# Build locally if the binary is missing or older than the source.
# ponytail: find -newer reruns the cross build only when something changed
if [[ ! -f "$BIN" ]] || \
   [[ -n "$(find "$SRC/src" "$SRC/Cargo.toml" -newer "$BIN" 2>/dev/null)" ]]; then
    echo "== cross-build (source newer than binary) =="
    "$SRC/scripts/build-cross.sh" >/dev/null
fi

ip=""
for cand in "$USB_IP" "$WIFI_IP"; do
    if ping -c1 -W1 "$cand" >/dev/null 2>&1; then ip="$cand"; break; fi
done
[[ -n "$ip" ]] || { echo "phone unreachable (tried $USB_IP, $WIFI_IP)" >&2; exit 1; }
PHONE="casey@$ip"
echo "== phone: $ip =="

echo "== binary =="
"${SCP[@]}" "$BIN" "$PHONE:/tmp/souveraine-xdev"
"${SSH[@]}" "$PHONE" 'sudo install -Dm755 /tmp/souveraine-xdev /usr/local/bin/souveraine && rm /tmp/souveraine-xdev'

echo "== systemd unit =="
# Repo unit runs %h/.local/bin (desktop dev install); point it at the shared binary.
sed 's|%h/.local/bin/souveraine|/usr/local/bin/souveraine|' "$UNIT" \
    | "${SSH[@]}" "$PHONE" 'install -Dm644 /dev/stdin ~/.config/systemd/user/souveraine.service'

echo "== ~/.souveraine data =="
# Excluding only seed-id was insufficient: the agent's private key lives in
# agents/<id>/seed/, which rsync would otherwise copy to the phone.
excludes=(--exclude 'seed-id' --exclude 'agents/*/seed')
[[ $clone_identity -eq 1 ]] && excludes=()
rsync -az -e "ssh -F /dev/null -i $HOME/.ssh/ani -o BatchMode=yes" "${excludes[@]}" \
    "$HOME/.souveraine/" "$PHONE:.souveraine/"

echo "== enable + start =="
"${SSH[@]}" "$PHONE" '
    systemctl --user daemon-reload
    systemctl --user enable souveraine.service 2>/dev/null || true
    systemctl --user restart souveraine.service
    sleep 2
    systemctl --user is-active souveraine.service
    curl -sf --max-time 3 http://127.0.0.1:8484/health && echo " health: ok"
'

echo "== done =="
if [[ $clone_identity -eq 0 ]]; then
    echo "note: no private keys were copied; this is not a commissioned federation node yet"
else
    echo "WARNING: copied machine and agent private keys for a deliberate same-instance migration"
fi
