#!/bin/bash
# ============================================================================
# srg-shell — 开启一个自带代理的子 shell
# ============================================================================
# 用法: srg-shell
#
# 进入后所有命令自动走代理，输入 exit 退出后代理自动消失。
# 不影响外层 shell 和其它终端窗口。
# ============================================================================

# ── Port auto-detection ─────────────────────────────────────────────
_srg_detect_port() {
    local base_port="__SRG_PORT__"
    if [ -n "${SRG_PROXY_PORT:-}" ]; then
        echo "$SRG_PROXY_PORT"
        return 0
    fi
    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
    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
    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 (输入 exit 退出，代理自动失效)"
echo "  HTTP_PROXY=$HTTP_PROXY"
echo ""

# 启动带标识提示符的子 shell
SRG_PS1="(srg) " exec bash --rcfile <(
    # 加载用户原有配置
    [ -f "$HOME/.bashrc" ] && cat "$HOME/.bashrc"
    # 覆盖 PS1 加上 (srg) 前缀
    echo 'export PS1="(srg) $PS1"'
)

