#!/bin/bash
# ============================================================================
# srg-on — 在当前 shell 开启代理
# ============================================================================
# 用法: source srg-on  或  . srg-on  或  srg-on (如果已注入 bashrc 函数)
#
# 仅影响当前 shell，退出后自动失效，不影响其它终端窗口。
# Git 也通过环境变量走代理，无需 git config --global。
# ============================================================================

# ── Port auto-detection ─────────────────────────────────────────────
# In VS Code integrated terminal: SRG_PROXY_PORT is injected by the
# extension, so we use it directly (zero overhead).
# In external SSH terminals: SRG_PROXY_PORT is absent, so we probe
# the configured port and nearby ports (+1..+10) using curl to verify
# the port is actually a proxy (not just any listening service).
# ────────────────────────────────────────────────────────────────────
_srg_detect_port() {
    local base_port="__SRG_PORT__"
    # Fast path: env var exists (VS Code terminal)
    if [ -n "${SRG_PROXY_PORT:-}" ]; then
        echo "$SRG_PROXY_PORT"
        return 0
    fi
    # Probe base_port with curl proxy handshake
    if curl --connect-timeout 1 -x "http://127.0.0.1:$base_port" http://localhost -so /dev/null 2>/dev/null; then
        echo "$base_port"
        return 0
    fi
    # Probe +1..+10 (matches Go daemon's max retry range)
    for offset in $(seq 1 10); do
        local test_port=$((base_port + offset))
        if curl --connect-timeout 1 -x "http://127.0.0.1:$test_port" http://localhost -so /dev/null 2>/dev/null; then
            echo "⚠ 端口自动探测: 使用 $test_port (配置端口 $base_port 不可达)" >&2
            echo "$test_port"
            return 0
        fi
    done
    # All probes failed — use base_port and let the user see the error
    echo "⚠ 代理端口 $base_port-$((base_port + 10)) 均不可达，SSH 隧道可能未建立" >&2
    echo "$base_port"
    return 1
}

_SRG_PORT=$(_srg_detect_port)
_SRG_ADDR="127.0.0.1:$_SRG_PORT"

export HTTP_PROXY="http://$_SRG_ADDR"
export HTTPS_PROXY="http://$_SRG_ADDR"
export http_proxy="http://$_SRG_ADDR"
export https_proxy="http://$_SRG_ADDR"
export ALL_PROXY="socks5://$_SRG_ADDR"
export all_proxy="socks5://$_SRG_ADDR"
export NO_PROXY="localhost,127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
export no_proxy="localhost,127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"

echo "✓ 代理已开启 (当前 shell)"
echo "  HTTP_PROXY=$HTTP_PROXY"
echo "  用 srg-off 关闭 | 退出 shell 自动失效"

