#!/data/data/com.termux/files/usr/bin/bash
# =============================================================================
# gcp-phone-teardown.sh — safely stop this phone's relay + SSH and RELEASE the
# VM port so the GCP relay (or the next phone) can reuse it immediately.
#
# Usage:
#   bash gcp-phone-teardown.sh                 # uses ~/.relay-port
#   bash gcp-phone-teardown.sh --port 2223
#   bash gcp-phone-teardown.sh --keep-sshd     # stop relay/free port, leave sshd up
#   bash gcp-phone-teardown.sh --disable-autostart   # also stop it coming back
#
# What it does, in order:
#   1) stop the relay loop (no more reconnects)
#   2) SSH to the VM and kill the session holding VM:PORT  -> port freed NOW
#      (otherwise the VM auto-reaps it in ~90s via ClientAlive)
#   3) stop the Termux sshd  (unless --keep-sshd)
#   4) release the wakelock
#   5) optionally neutralise autostart so it does not restart on next open/boot
# =============================================================================
set -uo pipefail

BIN="/data/data/com.termux/files/usr/bin"
CONF="$HOME/.gcp-relay.conf"; [ -f "$CONF" ] && . "$CONF"
VM_IP="${VM_IP:-136.67.4.216}"; VM_USER="${VM_USER:-karthik}"
VM_KEY="$HOME/.ssh/gcp_vm_key"
PORT=""; KEEP_SSHD=0; DISABLE_AUTOSTART=0

while [ $# -gt 0 ]; do
    case "$1" in
        --port)               PORT="${2:-}"; shift 2;;
        --keep-sshd)          KEEP_SSHD=1; shift;;
        --disable-autostart)  DISABLE_AUTOSTART=1; shift;;
        -h|--help) sed -n '2,22p' "$0"; exit 0;;
        *) echo "unknown arg: $1"; exit 1;;
    esac
done
[ -n "$PORT" ] || PORT="$(cat "$HOME/.relay-port" 2>/dev/null || true)"
[ -n "$PORT" ] || { echo "ERROR: no port given and ~/.relay-port missing"; exit 1; }

echo "==> [1/5] stopping relay loop for port $PORT"
PIDFILE="$HOME/.gcp_relay.${PORT}.pid"
if [ -f "$PIDFILE" ] && kill "$(cat "$PIDFILE")" 2>/dev/null; then
    echo "    stopped loop pid $(cat "$PIDFILE")"
fi
rm -f "$PIDFILE"
# belt-and-suspenders: kill any lingering ssh -R for this port (Termux side)
pkill -f "0.0.0.0:${PORT}:localhost" 2>/dev/null && echo "    killed lingering ssh -R" || true
rm -f "$HOME/.gcp_relay.${PORT}.lock"

echo "==> [2/5] releasing VM port $PORT (so the next phone can grab it)"
ssh -i "$VM_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 \
    "$VM_USER@$VM_IP" \
    "h=\$(sudo ss -tlnp 2>/dev/null | grep ':$PORT '); \
     if [ -n \"\$h\" ]; then \
        pid=\$(echo \"\$h\" | grep -oP 'pid=\K[0-9]+' | head -1); \
        sudo kill \$pid 2>/dev/null && echo '    VM port $PORT released'; \
     else echo '    VM port $PORT already free'; fi" 2>/dev/null \
    || echo "    (could not reach VM; it will auto-reap the port in ~90s)"

if [ "$KEEP_SSHD" = 0 ]; then
    echo "==> [3/5] stopping Termux sshd (drops any active inbound sessions)"
    pkill sshd 2>/dev/null && echo "    sshd stopped" || echo "    sshd not running"
else
    echo "==> [3/5] leaving Termux sshd running (--keep-sshd)"
fi

echo "==> [4/5] releasing wakelock"
"$BIN/termux-wake-unlock" 2>/dev/null && echo "    wakelock released" || true

if [ "$DISABLE_AUTOSTART" = 1 ]; then
    echo "==> [5/5] disabling autostart (boot script + ~/.bashrc block)"
    [ -f "$HOME/.termux/boot/00-start-relay.sh" ] && \
        mv "$HOME/.termux/boot/00-start-relay.sh" "$HOME/.termux/boot/00-start-relay.sh.disabled" && \
        echo "    boot script disabled"
    # comment out the bashrc autostart block
    if grep -qF ">>> gcp-relay autostart >>>" "$HOME/.bashrc" 2>/dev/null; then
        sed -i '/>>> gcp-relay autostart >>>/,/<<< gcp-relay autostart <<</ s/^/#gcpoff# /' "$HOME/.bashrc"
        echo "    ~/.bashrc autostart commented out"
    fi
else
    echo "==> [5/5] autostart left intact (will restart on next Termux open/boot)"
    echo "    use --disable-autostart to decommission permanently"
fi

echo "Done. Port $PORT is released on the VM."
