#!/bin/bash

# DNS代理一键部署脚本
# 用途：自动下载、安装并后台运行 dnsproxy

set -e

# 配置变量
DNSPROXY_VERSION="v0.77.0"
DOWNLOAD_URL="https://github.com/AdguardTeam/dnsproxy/releases/download/${DNSPROXY_VERSION}/dnsproxy-linux-amd64-${DNSPROXY_VERSION}.tar.gz"
INSTALL_DIR="/usr/local/bin"
WORK_DIR="/tmp/dnsproxy-install"
LOG_FILE="/var/log/dnsproxy.log"
DNS_PORT=5353

# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

# 检查是否为 root 用户
if [[ $EUID -ne 0 ]]; then
   echo_error "此脚本需要 root 权限运行"
   echo "请使用: sudo $0"
   exit 1
fi

# 检测系统类型
detect_system() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$ID
        VERSION_ID=$VERSION_ID
    elif [ -f /etc/redhat-release ]; then
        OS="centos"
        VERSION_ID="7"
    else
        OS="unknown"
    fi
    echo_info "检测到系统: $OS $VERSION_ID"
}

# 配置 iptables 防火墙
configure_iptables() {
    echo_info "配置 iptables 防火墙规则..."
    
    if ! command -v iptables &> /dev/null; then
        echo_warn "未找到 iptables 命令，跳过防火墙配置"
        return
    fi
    
    # 添加 TCP 规则（如果不存在）
    if ! iptables -C INPUT -p tcp --dport ${DNS_PORT} -j ACCEPT 2>/dev/null; then
        iptables -I INPUT -p tcp --dport ${DNS_PORT} -j ACCEPT
        echo_info "已添加 TCP ${DNS_PORT} 端口规则"
    else
        echo_info "TCP ${DNS_PORT} 端口规则已存在"
    fi
    
    # 添加 UDP 规则（如果不存在）
    if ! iptables -C INPUT -p udp --dport ${DNS_PORT} -j ACCEPT 2>/dev/null; then
        iptables -I INPUT -p udp --dport ${DNS_PORT} -j ACCEPT
        echo_info "已添加 UDP ${DNS_PORT} 端口规则"
    else
        echo_info "UDP ${DNS_PORT} 端口规则已存在"
    fi
    
    # 保存 iptables 规则
    if [ "$OS" = "centos" ] && [ "${VERSION_ID%%.*}" = "7" ]; then
        # CentOS 7
        if command -v service &> /dev/null; then
            service iptables save &> /dev/null && echo_info "iptables 规则已保存 (CentOS 7)" || echo_warn "iptables 规则保存失败"
        fi
    elif [ "$OS" = "ubuntu" ] || [ "$OS" = "debian" ]; then
        # Ubuntu/Debian
        if command -v netfilter-persistent &> /dev/null; then
            netfilter-persistent save &> /dev/null && echo_info "iptables 规则已保存 (netfilter-persistent)" || echo_warn "iptables 规则保存失败"
        elif command -v iptables-save &> /dev/null; then
            mkdir -p /etc/iptables
            iptables-save > /etc/iptables/rules.v4 2>/dev/null && echo_info "iptables 规则已保存 (/etc/iptables/rules.v4)" || echo_warn "iptables 规则保存失败"
        fi
    else
        echo_warn "未识别的系统，iptables 规则可能在重启后丢失"
    fi
    
    echo_info "✅ iptables 防火墙配置完成"
}

# 检查必要的命令
for cmd in wget tar; do
    if ! command -v $cmd &> /dev/null; then
        echo_error "未找到命令: $cmd，请先安装"
        exit 1
    fi
done

# 检测系统
detect_system

# 停止已运行的 dnsproxy 进程
if pgrep -x "dnsproxy" > /dev/null; then
    echo_warn "检测到正在运行的 dnsproxy，正在停止..."
    pkill -9 dnsproxy
    sleep 1
fi

# 创建工作目录
echo_info "创建临时工作目录..."
mkdir -p "$WORK_DIR"
cd "$WORK_DIR"

# 下载 dnsproxy
FILENAME="dnsproxy-linux-amd64-${DNSPROXY_VERSION}.tar.gz"
echo_info "下载 dnsproxy ${DNSPROXY_VERSION}..."
wget "$DOWNLOAD_URL" -O "$FILENAME" || {
    echo_error "下载失败"
    exit 1
}

# 解压文件
echo_info "解压文件..."
tar -xzf "$FILENAME"

# 安装到系统目录
echo_info "安装 dnsproxy 到 ${INSTALL_DIR}..."
mv linux-amd64/dnsproxy "${INSTALL_DIR}/"
chmod +x "${INSTALL_DIR}/dnsproxy"

# 清理临时文件
cd /
rm -rf "$WORK_DIR"

# 配置防火墙
configure_iptables

# 创建日志文件
touch "$LOG_FILE"

# 后台启动服务
echo_info "启动 DNS 代理服务（后台运行）..."
nohup dnsproxy \
    --port=${DNS_PORT} \
    --listen=0.0.0.0 \
    --upstream=https://1.1.1.1/dns-query \
    --upstream=https://8.8.8.8/dns-query \
    --upstream-mode=parallel \
    --cache \
    --edns \
    --insecure \
    --verbose \
    > "$LOG_FILE" 2>&1 &

sleep 2

# 验证服务状态
if pgrep -x "dnsproxy" > /dev/null; then
    PID=$(pgrep -x "dnsproxy")
    echo ""
    echo_info "✅ DNS 代理服务已成功启动！"
    echo_info "进程 ID: $PID"
    echo_info "监听端口: ${DNS_PORT}"
    echo_info "日志文件: $LOG_FILE"
    echo ""
    echo_info "如需停止服务，请运行: pkill dnsproxy"
    echo_info "查看日志: tail -f $LOG_FILE"
    echo_info "查看端口: netstat -tulnp | grep ${DNS_PORT}"
else
    echo_error "服务启动失败，请查看日志: cat $LOG_FILE"
    exit 1
fi
