#!/bin/bash
#***************************************************************#
# ScriptName: setporxy.sh
# Author: xhy
# Create Date: 2025-07-17 18:57
# Modify Author: xhy
# Modify Date: 2025-09-03 17:25
# Version: v2
#***************************************************************#

PROXY_ADDR="172.24.8.1"
PROXY_PORT="10808"
# 定义不经过代理的私有地址段（CIDR格式）
PRIVATE_CIDR="10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
# 添加本地地址和私有域名
LOCAL_ADDR="localhost,127.0.0.1,::1,.internal,.local,.lan"

start_proxy() {
    echo "✅ 启用代理: ${PROXY_ADDR}:${PROXY_PORT}"
    export http_proxy="http://${PROXY_ADDR}:${PROXY_PORT}"
    export https_proxy="http://${PROXY_ADDR}:${PROXY_PORT}"
    # 设置no_proxy排除私有地址
    export no_proxy="${PRIVATE_CIDR},${LOCAL_ADDR}"
    export NO_PROXY="${no_proxy}"  # 兼容大写变量
    
    echo "代理已启用！当前设置:"
    echo "http_proxy  = ${http_proxy}"
    echo "https_proxy = ${https_proxy}"
    echo "no_proxy    = ${no_proxy}"
}

stop_proxy() {
    echo "⛔ 禁用代理"
    unset http_proxy https_proxy no_proxy NO_PROXY
    echo "代理已禁用！"
}

show_help() {
    echo "用法:"
    echo "  $0 start   启用代理并排除私有地址"
    echo "  $0 stop    禁用代理"
    echo "  $0 status  查看当前代理状态"
}

check_status() {
    if [ -n "${http_proxy}" ]; then
        echo "🟢 代理已启用"
        echo "http_proxy  = ${http_proxy:-未设置}"
        echo "https_proxy = ${https_proxy:-未设置}"
        echo "no_proxy    = ${no_proxy:-未设置}"
    else
        echo "🔴 代理未启用"
        echo "提示：私有地址段始终直连"
    fi
}

case "$1" in
    start)  start_proxy ;;
    stop)   stop_proxy ;;
    status) check_status ;;
    *)      show_help; exit 1 ;;
esac
