#!/usr/bin/env bash
# Relay no VPS: publica na tailnet o porto que o kernel Kaggle abrir via tunnel reverso.
# Uso: vps-relay.sh start <porta_tailnet> <porta_tunnel>
#      vps-relay.sh stop
set -uo pipefail
TSIP=100.78.193.88
ACT="${1:-status}"
case "$ACT" in
  start)
    PUB="${2:-18098}"; TUN="${3:-18099}"
    # mata socat antigo (por PID gravado, nunca por pkill -f que se auto-mata)
    [ -f /tmp/relay.pid ] && kill "$(cat /tmp/relay.pid)" 2>/dev/null
    rm -f /tmp/relay.pid
    nohup socat "TCP-LISTEN:${PUB},fork,reuseaddr,bind=${TSIP}" "TCP:127.0.0.1:${TUN}" \
      >/tmp/relay.log 2>&1 &
    echo $! > /tmp/relay.pid
    sleep 1
    if ss -tln | grep -q ":${PUB}"; then
      echo "RELAY_OK pub=${TSIP}:${PUB} -> 127.0.0.1:${TUN} pid=$(cat /tmp/relay.pid)"
    else
      echo "RELAY_FAIL"; cat /tmp/relay.log | tail -3
    fi
    ;;
  stop)
    [ -f /tmp/relay.pid ] && kill "$(cat /tmp/relay.pid)" 2>/dev/null && echo "socat morto"
    rm -f /tmp/relay.pid
    ;;
  status)
    ss -tln | grep -E ":1809[89]" || echo "(relay inactivo)"
    ;;
esac
