#!/bin/bash
# gcp_relay.sh — keep a single reverse SSH tunnel to the GCP relay VM alive.
# Exposes this phone's sshd (localhost:8021) on the VM's public IP.
#
# Port selection (so MULTIPLE phones can share one VM, each on its own port):
#   - default 2222
#   - override per-phone by writing the port into /root/.relay-port
#   - or pass as 2nd arg:  gcp_relay.sh <VM_IP> <PORT>
# Connect from anywhere:  ssh -i pc-access-key root@<VM_IP> -p <PORT>
#
# VM IP: if it ever changes (VM stop/start), update below or pass as 1st arg:
#   gcloud compute instances list --format='value(EXTERNAL_IP)'
#
# Singleton per port via flock (pgrep/pkill do NOT work in this proot env, so a
# file lock — not process scanning — is what guarantees no duplicate tunnels).

VM_IP="${1:-136.67.4.216}"
REMOTE_PORT="${2:-$(cat /root/.relay-port 2>/dev/null || echo 2222)}"
LOCK="/root/.gcp_relay.${REMOTE_PORT}.lock"

# --- single-instance lock (fcntl-based, works without a usable /proc) ---
exec 9>"$LOCK"
if ! flock -n 9; then
    echo "[$(date '+%F %T')] gcp_relay for port $REMOTE_PORT already running — exiting"
    exit 0
fi

while true; do
    echo "[$(date '+%F %T')] connecting tunnel $VM_IP:$REMOTE_PORT -> localhost:8021 ..."
    # 9<&- so the ssh child does not hold the lock (only the loop should).
    ssh -i /root/.ssh/google_compute_engine \
        -o StrictHostKeyChecking=accept-new \
        -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
        -o ExitOnForwardFailure=yes -N \
        -R "0.0.0.0:${REMOTE_PORT}:localhost:8021" "karthik@$VM_IP" 9<&-
    echo "[$(date '+%F %T')] tunnel dropped (exit $?), retrying in 5s"
    sleep 5
done
