#!/bin/zsh
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="$ROOT_DIR/.env"

load_env_value() {
  local key="$1"
  if [[ -f "$ENV_FILE" ]]; then
    /usr/bin/awk -F= -v k="$key" '$1 == k { sub(/^[^=]*=/, ""); print; exit }' "$ENV_FILE"
  fi
}

VPS_HOST="$(load_env_value CODEXMOBILE_VPS_HOST)"
if [[ -z "$VPS_HOST" ]]; then
  VPS_HOST="$(load_env_value CODEXBOT_VPS_HOST)"
fi
if [[ -z "$VPS_HOST" ]]; then
  echo "Missing CODEXMOBILE_VPS_HOST or CODEXBOT_VPS_HOST in $ENV_FILE" >&2
  exit 2
fi

REMOTE_PORT="$(load_env_value CODEXMOBILE_VPS_TUNNEL_PORT)"
if [[ -z "$REMOTE_PORT" ]]; then
  REMOTE_PORT="$(load_env_value CODEXBOT_VPS_TUNNEL_PORT)"
fi
if [[ -z "$REMOTE_PORT" ]]; then
  REMOTE_PORT="18765"
fi

LOCAL_PORT="$(load_env_value CODEXMOBILE_MAC_SERVICE_PORT)"
if [[ -z "$LOCAL_PORT" ]]; then
  LOCAL_PORT="$(load_env_value CODEXBOT_MAC_SERVICE_PORT)"
fi
if [[ -z "$LOCAL_PORT" ]]; then
  LOCAL_PORT="8765"
fi

REMOTE_USER="$(load_env_value CODEXMOBILE_VPS_USER)"
if [[ -z "$REMOTE_USER" ]]; then
  REMOTE_USER="$(load_env_value CODEXBOT_VPS_USER)"
fi
if [[ -z "$REMOTE_USER" ]]; then
  REMOTE_USER="root"
fi

REMOTE_TARGET="${REMOTE_USER}@${VPS_HOST}"

# Network drops can leave an orphaned sshd on the VPS holding the remote
# forwarding port. Clear only sshd listeners on that exact port before opening
# a new reverse tunnel.
/usr/bin/ssh \
  -o BatchMode=yes \
  -o ConnectTimeout=8 \
  -o StrictHostKeyChecking=accept-new \
  "$REMOTE_TARGET" \
  "pids=\$(ss -ltnp 2>/dev/null | awk '\$4 ~ /:${REMOTE_PORT}\$/ && /sshd/ { if (match(\$0, /pid=[0-9]+/)) { print substr(\$0, RSTART + 4, RLENGTH - 4) } }'); if [ -n \"\$pids\" ]; then kill \$pids 2>/dev/null || true; sleep 1; fi" \
  >/dev/null 2>&1 || true

exec /usr/bin/ssh \
  -NT \
  -o ExitOnForwardFailure=yes \
  -o ServerAliveInterval=30 \
  -o ServerAliveCountMax=3 \
  -o StrictHostKeyChecking=accept-new \
  -R "127.0.0.1:${REMOTE_PORT}:127.0.0.1:${LOCAL_PORT}" \
  "$REMOTE_TARGET"
