#!/data/data/com.termux/files/usr/bin/bash
# =============================================================================
# gcp-phone-teardown-ubuntu.sh — stop the Ubuntu-based relay + sshd on this
# phone and RELEASE the VM port so the next phone can reuse it immediately.
#
# Works entirely from the Termux side (proot has no PID namespace, so pids and
# the VM key inside the Ubuntu rootfs are reachable from here).
#
# Usage:
#   bash gcp-phone-teardown-ubuntu.sh                 # auto-detect port + rootfs
#   bash gcp-phone-teardown-ubuntu.sh --port 2224
#   bash gcp-phone-teardown-ubuntu.sh --keep-sshd
#   bash gcp-phone-teardown-ubuntu.sh --disable-autostart
#   options: --ubuntu-rootfs PATH  --distro-type proot-distro|start-ubuntu22
# =============================================================================
set -uo pipefail

BIN="/data/data/com.termux/files/usr/bin"
PREFIX="/data/data/com.termux/files/usr"
PORT=""; ROOTFS=""; DISTRO_TYPE=""; KEEP_SSHD=0; DISABLE_AUTOSTART=0

while [ $# -gt 0 ]; do
    case "$1" in
        --port)              PORT="${2:-}"; shift 2;;
        --ubuntu-rootfs)     ROOTFS="${2:-}"; shift 2;;
        --distro-type)       DISTRO_TYPE="${2:-}"; shift 2;;
        --keep-sshd)         KEEP_SSHD=1; shift;;
        --disable-autostart) DISABLE_AUTOSTART=1; shift;;
        -h|--help) sed -n '2,20p' "$0"; exit 0;;
        *) echo "unknown arg: $1"; exit 1;;
    esac
done

# locate the ubuntu rootfs
if [ -z "$ROOTFS" ]; then
    if [ -d "$PREFIX/var/lib/proot-distro/installed-rootfs/ubuntu/root" ]; then
        ROOTFS="$PREFIX/var/lib/proot-distro/installed-rootfs/ubuntu"; DISTRO_TYPE="${DISTRO_TYPE:-proot-distro}"
    elif [ -d "$HOME/ubuntu22-fs/root" ]; then
        ROOTFS="$HOME/ubuntu22-fs"; DISTRO_TYPE="${DISTRO_TYPE:-start-ubuntu22}"
    else
        echo "ERROR: could not find Ubuntu rootfs; pass --ubuntu-rootfs"; exit 1
    fi
fi
UROOT="$ROOTFS/root"
[ -n "$PORT" ] || PORT="$(cat "$UROOT/.relay-port" 2>/dev/null || true)"
[ -n "$PORT" ] || { echo "ERROR: no port given and $UROOT/.relay-port missing"; exit 1; }

VM_IP="136.67.4.216"; VM_USER="karthik"
[ -f "$UROOT/.gcp-relay.conf" ] && . "$UROOT/.gcp-relay.conf"
VM_KEY="$UROOT/.ssh/gcp_vm_key"

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

echo "==> [2/5] releasing VM port $PORT"
if [ -f "$VM_KEY" ]; then
    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 auto-reaps in ~90s)"
else
    echo "    VM key not found ($VM_KEY); VM will auto-reap the port in ~90s"
fi

if [ "$KEEP_SSHD" = 0 ]; then
    echo "==> [3/5] stopping Ubuntu sshd"
    if [ -f "$ROOTFS/run/sshd.pid" ] && kill "$(cat "$ROOTFS/run/sshd.pid")" 2>/dev/null; then
        echo "    Ubuntu sshd stopped"
    else
        echo "    Ubuntu sshd not running (or pid file absent)"
    fi
else
    echo "==> [3/5] leaving Ubuntu 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"
    [ -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"
    if grep -qF ">>> gcp-relay enter-ubuntu >>>" "$HOME/.bashrc" 2>/dev/null; then
        sed -i '/>>> gcp-relay enter-ubuntu >>>/,/<<< gcp-relay enter-ubuntu <<</ s/^/#gcpoff# /' "$HOME/.bashrc"
        echo "    Termux ~/.bashrc auto-enter commented out"
    fi
    if grep -qF ">>> gcp-relay autostart >>>" "$UROOT/.bashrc" 2>/dev/null; then
        sed -i '/>>> gcp-relay autostart >>>/,/<<< gcp-relay autostart <<</ s/^/#gcpoff# /' "$UROOT/.bashrc"
        echo "    Ubuntu /root/.bashrc autostart commented out"
    fi
else
    echo "==> [5/5] autostart left intact (use --disable-autostart to decommission)"
fi

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