#!/usr/bin/env bash
# start_nordvpn_socks_bridge — Levanta proxy HTTP local sin auth que reenvía a SOCKS5 NordVPN con auth via gost v3.
# Resuelve la limitacion de Chrome que no soporta SOCKS5-con-auth.
set -euo pipefail

# --- defaults ---
PORT=8889
SOCKS_HOST="socks-nl1.nordvpn.com"
SOCKS_PORT=1080
VPN_USER="${NORDVPN_SOCKS_USER:-}"
VPN_PASS="${NORDVPN_SOCKS_PASS:-}"

# --- parse args ---
while [[ $# -gt 0 ]]; do
    case "$1" in
        --port)       PORT="$2";       shift 2 ;;
        --socks-host) SOCKS_HOST="$2"; shift 2 ;;
        --socks-port) SOCKS_PORT="$2"; shift 2 ;;
        --user)       VPN_USER="$2";   shift 2 ;;
        --pass)       VPN_PASS="$2";   shift 2 ;;
        *) echo "Unknown arg: $1" >&2; exit 1 ;;
    esac
done

# --- validate creds ---
if [[ -z "$VPN_USER" ]]; then
    echo "error: NORDVPN_SOCKS_USER not set. Use --user or export NORDVPN_SOCKS_USER" >&2
    exit 1
fi
if [[ -z "$VPN_PASS" ]]; then
    echo "error: NORDVPN_SOCKS_PASS not set. Use --pass or export NORDVPN_SOCKS_PASS" >&2
    exit 1
fi

LOG_FILE="/tmp/nordvpn_socks_bridge_${PORT}.log"

# --- check idempotencia: ya escucha? ---
if ss -ltn 2>/dev/null | grep -q ":${PORT} "; then
    echo "{\"proxy_url\":\"http://127.0.0.1:${PORT}\",\"pid\":null,\"socks_host\":\"${SOCKS_HOST}\",\"status\":\"already_running\"}"
    exit 0
fi

# --- asegurar gost ---
GOST_BIN=""
if command -v gost &>/dev/null; then
    GOST_BIN="$(command -v gost)"
elif [[ -x "$HOME/.local/bin/gost" ]]; then
    GOST_BIN="$HOME/.local/bin/gost"
else
    echo "gost not found, downloading v3.0.0 linux amd64..." >&2
    GOST_URL="https://github.com/go-gost/gost/releases/download/v3.0.0/gost_3.0.0_linux_amd64.tar.gz"
    TMP_DIR="$(mktemp -d)"
    curl -fsSL "$GOST_URL" -o "$TMP_DIR/gost.tar.gz" >&2
    tar -xzf "$TMP_DIR/gost.tar.gz" -C "$TMP_DIR" >&2
    mkdir -p "$HOME/.local/bin"
    cp "$TMP_DIR/gost" "$HOME/.local/bin/gost"
    chmod +x "$HOME/.local/bin/gost"
    rm -rf "$TMP_DIR"
    GOST_BIN="$HOME/.local/bin/gost"
    echo "gost installed to $GOST_BIN" >&2
fi

# --- url-encode user y pass (puede tener caracteres especiales) ---
url_encode() {
    python3 -c "import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=''))" "$1"
}

ENC_USER="$(url_encode "$VPN_USER")"
ENC_PASS="$(url_encode "$VPN_PASS")"

# --- lanzar gost en background ---
nohup "$GOST_BIN" \
    -L "http://:${PORT}" \
    -F "socks5://${ENC_USER}:${ENC_PASS}@${SOCKS_HOST}:${SOCKS_PORT}" \
    >"$LOG_FILE" 2>&1 &
GOST_PID=$!
disown $GOST_PID

# --- esperar ~2s y verificar que el puerto escucha ---
sleep 2
if ! ss -ltn 2>/dev/null | grep -q ":${PORT} "; then
    echo "error: gost did not start. Last lines of $LOG_FILE:" >&2
    tail -10 "$LOG_FILE" >&2
    exit 1
fi

echo "{\"proxy_url\":\"http://127.0.0.1:${PORT}\",\"pid\":${GOST_PID},\"socks_host\":\"${SOCKS_HOST}\",\"status\":\"running\"}"
