#!/usr/bin/env bash
# tower-tunnel.sh - Persistent reverse tunnel from Mac to Herm
VPS="root@143.198.27.163"

# Kill existing tunnel
pkill -f "ssh.*-R.*400[0-9].*143.198.27.163" 2>/dev/null
sleep 2

echo "Starting reverse tunnel to VPS ($VPS)..."

# Tunnel ports:
#  4000 - Evennia telnet
#  4001 - Evennia web
#  4002 - Evennia websocket
nohup ssh -o ExitOnForwardFailure=yes \
    -o ServerAliveInterval=30 \
    -o ServerAliveCountMax=3 \
    -N -R 4000:127.0.0.1:4000 \
       -R 4001:127.0.0.1:4001 \
       -R 4002:127.0.0.1:4002 \
       "$VPS" > /tmp/tower-tunnel.log 2>&1 &

TUNNEL_PID=$!
sleep 3

# Verify
if nc -z -w 3 127.0.0.1 4000 2>/dev/null; then
    echo "Tunnel UP (PID: $TUNNEL_PID)"
    echo "Telnet:      nc 143.198.27.163 4000"
    echo "Web client:  http://143.198.27.163:4001/webclient"
else
    echo "Tunnel FAILED"
    cat /tmp/tower-tunnel.log
    exit 1
fi
