#!/bin/bash

# =============================================
# SOCKS5代理服务器一键部署脚本 (香港服务器)
# 功能：在香港服务器部署Dante SOCKS5代理服务
# =============================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置参数
SOCKS_PORT="1080"
INSTALL_LOG="/tmp/socks5_install.log"
CONFIG_FILE="/etc/danted.conf"
SERVICE_NAME="danted"

log() {
    echo -e "${GREEN}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a $INSTALL_LOG
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a $INSTALL_LOG
}

error() {
    echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a $INSTALL_LOG
    exit 1
}

check_os() {
    log "检测操作系统..."
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$NAME
        VER=$VERSION_ID
    else
        OS=$(uname -s)
        VER=$(uname -r)
    fi
    log "操作系统: $OS, 版本: $VER"
}

install_dependencies() {
    log "安装系统依赖..."
    
    if command -v apt-get &> /dev/null; then
        apt-get update >> $INSTALL_LOG 2>&1
        apt-get install -y dante-server net-tools >> $INSTALL_LOG 2>&1
    elif command -v yum &> /dev/null; then
        yum install -y epel-release >> $INSTALL_LOG 2>&1
        yum install -y dante-server net-tools >> $INSTALL_LOG 2>&1
    elif command -v dnf &> /dev/null; then
        dnf install -y dante-server net-tools >> $INSTALL_LOG 2>&1
    else
        error "不支持的包管理器，请手动安装dante-server"
    fi
}

get_external_ip() {
    log "获取服务器公网IP..."
    EXTERNAL_IP=$(curl -s -4 ifconfig.co)
    if [ -z "$EXTERNAL_IP" ]; then
        EXTERNAL_IP=$(hostname -I | awk '{print $1}')
    fi
    log "服务器公网IP: $EXTERNAL_IP"
}

configure_dante() {
    log "配置Dante SOCKS5服务器..."
    
    # 备份原有配置
    if [ -f "$CONFIG_FILE" ]; then
        cp "$CONFIG_FILE" "${CONFIG_FILE}.backup.$(date +%Y%m%d%H%M%S)"
    fi
    
    # 创建新的配置文件
    cat > "$CONFIG_FILE" << EOF
# Dante SOCKS5 服务器配置
# 生成时间: $(date)

logoutput: syslog
internal: 0.0.0.0 port = $SOCKS_PORT
external: $EXTERNAL_IP

# 认证方法: none (无需认证), username (用户名密码)
method: username none

# 客户端规则
client pass {
    from: 0.0.0.0/0 to: 0.0.0.0/0
    log: connect disconnect error
}

# 通行规则
pass {
    from: 0.0.0.0/0 to: 0.0.0.0/0
    command: bind connect udpassociate
    log: connect disconnect error
    method: none
}

# 阻止规则
block {
    from: 0.0.0.0/0 to: 0.0.0.0/0
    log: connect error
}
EOF

    log "Dante配置文件已生成: $CONFIG_FILE"
}

configure_firewall() {
    log "配置防火墙..."
    
    if command -v ufw &> /dev/null; then
        ufw allow $SOCKS_PORT/tcp >> $INSTALL_LOG 2>&1
        log "UFW防火墙已开放端口: $SOCKS_PORT"
    elif command -v firewall-cmd &> /dev/null; then
        firewall-cmd --permanent --add-port=$SOCKS_PORT/tcp >> $INSTALL_LOG 2>&1
        firewall-cmd --reload >> $INSTALL_LOG 2>&1
        log "FirewallD已开放端口: $SOCKS_PORT"
    elif command -v iptables &> /dev/null; then
        iptables -I INPUT -p tcp --dport $SOCKS_PORT -j ACCEPT >> $INSTALL_LOG 2>&1
        log "iptables已临时开放端口: $SOCKS_PORT"
        warn "iptables规则需要持久化保存"
    else
        warn "未找到已知的防火墙工具，请手动开放端口: $SOCKS_PORT"
    fi
}

start_service() {
    log "启动Dante服务..."
    
    systemctl enable $SERVICE_NAME >> $INSTALL_LOG 2>&1
    systemctl restart $SERVICE_NAME >> $INSTALL_LOG 2>&1
    
    # 检查服务状态
    if systemctl is-active --quiet $SERVICE_NAME; then
        log "Dante服务启动成功"
    else
        error "Dante服务启动失败，请检查日志: journalctl -u $SERVICE_NAME"
    fi
    
    # 检查端口监听
    sleep 2
    if netstat -ln | grep ":$SOCKS_PORT" &> /dev/null || ss -ln | grep ":$SOCKS_PORT" &> /dev/null; then
        log "SOCKS5服务正在监听端口: $SOCKS_PORT"
    else
        warn "SOCKS5服务端口未正常监听，请检查配置"
    fi
}

generate_client_script() {
    log "生成客户端配置脚本..."
    
    CLIENT_SCRIPT="/tmp/setup-proxy-client.sh"
    
    cat > "$CLIENT_SCRIPT" << EOF
#!/bin/bash
# =============================================
# SOCKS5代理客户端配置脚本 (北京服务器使用)
# 香港服务器: $EXTERNAL_IP:$SOCKS_PORT
# =============================================

echo "🔧 配置SOCKS5代理客户端..."

# 设置环境变量 (临时生效)
export http_proxy=socks5://$EXTERNAL_IP:$SOCKS_PORT
export https_proxy=socks5://$EXTERNAL_IP:$SOCKS_PORT
export HTTP_PROXY=socks5://$EXTERNAL_IP:$SOCKS_PORT
export HTTPS_PROXY=socks5://$EXTERNAL_IP:$SOCKS_PORT
export ALL_PROXY=socks5://$EXTERNAL_IP:$SOCKS_PORT

echo "✅ 已设置环境变量代理:"
echo "   http_proxy=$http_proxy"
echo "   https_proxy=$https_proxy"

# 测试代理连接
echo "🧪 测试代理连接..."
if command -v curl &> /dev/null; then
    echo "通过代理访问Google测试..."
    curl -x socks5://$EXTERNAL_IP:$SOCKS_PORT --connect-timeout 10 -s -I https://www.google.com | head -1
else
    echo "⚠️  未找到curl，跳过连接测试"
fi

echo ""
echo "💡 使用方法:"
echo "1. 当前终端会话已配置代理"
echo "2. 手动测试: curl -x socks5://$EXTERNAL_IP:$SOCKS_PORT https://api.ip.sb/ip"
echo "3. 永久生效: 将环境变量添加到 ~/.bashrc 或 ~/.profile"
echo ""
echo "🛑 取消代理: unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY"
EOF

    chmod +x "$CLIENT_SCRIPT"
    log "客户端配置脚本已生成: $CLIENT_SCRIPT"
}

show_summary() {
    echo ""
    echo -e "${GREEN}🎉 SOCKS5代理部署完成!${NC}"
    echo "=========================================="
    echo -e "${BLUE}服务器信息:${NC}"
    echo "  IP地址: $EXTERNAL_IP"
    echo "  SOCKS5端口: $SOCKS_PORT"
    echo "  协议: SOCKS5"
    echo "  认证: 无"
    echo ""
    echo -e "${BLUE}下一步操作:${NC}"
    echo "1. 在北京服务器上下载客户端配置脚本:"
    echo "   scp root@$EXTERNAL_IP:/tmp/setup-proxy-client.sh ."
    echo "2. 在北京服务器上运行: ./setup-proxy-client.sh"
    echo ""
    echo -e "${YELLOW}测试命令:${NC}"
    echo "  curl -x socks5://$EXTERNAL_IP:$SOCKS_PORT https://api.ip.sb/ip"
    echo ""
    echo -e "${GREEN}安装日志: $INSTALL_LOG${NC}"
    echo "=========================================="
}

main() {
    echo -e "${GREEN}🚀 开始部署SOCKS5代理服务器...${NC}"
    echo "安装日志: $INSTALL_LOG"
    echo ""
    
    check_os
    install_dependencies
    get_external_ip
    configure_dante
    configure_firewall
    start_service
    generate_client_script
    show_summary
}

# 执行主函数
main "$@"