#!/bin/bash
# Debian12 一键安装 WireGuard + WireGuard UI
# 作者：KDRNN
# 最后更新：2025-04-06

set -e
LOGFILE="/var/log/wireguard-install.log"
exec > >(tee -a "$LOGFILE") 2>&1

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}[错误] 本脚本必须以 root 权限运行！${NC}" 
   exit 1
fi

echo -e "${RED}==================================================${NC}"
echo -e "${RED}                    重要提示                      ${NC}"
echo -e "${RED}==================================================${NC}"
echo -e "${YELLOW}运行此脚本将会:${NC}"
echo -e "1. 关闭所有现有防火墙"
echo -e "2. 安装并使用iptables作为防火墙"
echo -e "3. 可能放行所有端口 (取决于您的配置)"
echo -e "4. 以上为可选操作，若拒绝则最终可能需要自行配置防火墙规则"
echo -e ""
echo -e "${RED}请确保您已了解这些风险并做好相应准备！${NC}"
echo -e ""

read -p "是否继续执行? [Y/n]: " confirm
confirm=${confirm:-y}
if [[ "${confirm,,}" != "y" ]]; then
    echo -e "${YELLOW}用户取消执行，脚本退出。${NC}"
    exit 0
fi

echo -e "${YELLOW}[1/8] 更新系统并安装依赖包...${NC}"
sleep 1
apt-get update
apt-get install -y vim wget curl tar wireguard qrencode

echo -e "${YELLOW}[2/8] 检测并关闭系统防火墙...${NC}"

echo -e "${YELLOW}是否要禁用所有防火墙并清理规则？${NC}"
echo -e "如果选择否(n)，您需要自行配置防火墙规则"
read -p "请选择[Y/n] (默认Y): " disable_firewall
disable_firewall=${disable_firewall:-y}

if [[ "${disable_firewall,,}" == "y" ]]; then

if systemctl is-active --quiet ufw 2>/dev/null || dpkg -l | grep -q "ufw"; then
    echo -e "${YELLOW}→ 检测到 ufw，正在关闭...${NC}"
    ufw disable 2>/dev/null || true
    ufw reset --force 2>/dev/null || true
    systemctl stop ufw 2>/dev/null || true
    systemctl disable ufw 2>/dev/null || true
fi

if systemctl is-active --quiet firewalld 2>/dev/null || dpkg -l | grep -q "firewalld"; then
    echo -e "${YELLOW}→ 检测到 firewalld，正在关闭...${NC}"
    systemctl stop firewalld 2>/dev/null || true
    systemctl disable firewalld 2>/dev/null || true
fi

if command -v iptables >/dev/null 2>&1; then
    echo -e "${YELLOW}→ 清理 iptables 规则...${NC}"
    iptables -F
    iptables -X
    iptables -t nat -F
    iptables -t nat -X
    iptables -t mangle -F
    iptables -t mangle -X
    iptables -P INPUT ACCEPT
    iptables -P FORWARD ACCEPT
    iptables -P OUTPUT ACCEPT
fi

if command -v nft >/dev/null 2>&1; then
    echo -e "${YELLOW}→ 清理 nftables 规则...${NC}"
    nft flush ruleset 2>/dev/null || true
fi

for service in ufw firewalld iptables nftables; do
    if systemctl is-active --quiet "$service" 2>/dev/null; then
        systemctl stop "$service" 2>/dev/null || true
        systemctl disable "$service" 2>/dev/null || true
    fi
done


echo -e "${GREEN}✔ 所有检测到的防火墙服务已关闭${NC}"
apt-get install -y iptables
echo -e "${GREEN}✔ 已安装iptables${NC}"
fi

echo -e "${YELLOW}[3/8] 配置IP转发...${NC}"
sleep 1
sed -i '/net.ipv4.ip_forward/s/^#//g' /etc/sysctl.conf
sysctl -p | grep "net.ipv4.ip_forward"
echo -e "${GREEN}✔ IP转发已启用${NC}"

echo -e "${YELLOW}[4/8] 正在安装 WireGuard UI...${NC}\r"
sleep 1
mkdir -p /opt/wireguard-ui
cd /opt/wireguard-ui
wget https://github.com/ngoduykhanh/wireguard-ui/releases/download/v0.6.2/wireguard-ui-v0.6.2-linux-amd64.tar.gz
tar -zxvf /opt/wireguard-ui/wireguard-ui-v0.6.2-linux-amd64.tar.gz

DEFAULT_BIND_ADDRESS="0.0.0.0:5050"
DEFAULT_SMTP_AUTH_TYPE="LOGIN"
DEFAULT_SMTP_ENCRYPTION="SSL"

read -p "请输入绑定地址 [默认: $DEFAULT_BIND_ADDRESS]: " BIND_ADDRESS
BIND_ADDRESS=${BIND_ADDRESS:-$DEFAULT_BIND_ADDRESS}

WGUI_PORT=$(echo "$BIND_ADDRESS" | awk -F: '{print $2}')

read -p "请输入发件邮箱地址 (留空则不配置): " EMAIL_FROM_ADDRESS
read -p "请输入发件人名称 (留空则不配置): " EMAIL_FROM_NAME
read -p "请输入SMTP服务器地址 (留空则不配置): " SMTP_HOSTNAME
read -p "请输入SMTP端口 (留空则不配置): " SMTP_PORT
read -p "请输入SMTP用户名 (留空则不配置): " SMTP_USERNAME
read -p "请输入SMTP密码 (留空则不配置): " SMTP_PASSWORD

read -p "请输入SMTP认证类型 [默认: $DEFAULT_SMTP_AUTH_TYPE]: " SMTP_AUTH_TYPE
SMTP_AUTH_TYPE=${SMTP_AUTH_TYPE:-$DEFAULT_SMTP_AUTH_TYPE}

read -p "请输入SMTP加密方式 [默认: $DEFAULT_SMTP_ENCRYPTION]: " SMTP_ENCRYPTION
SMTP_ENCRYPTION=${SMTP_ENCRYPTION:-$DEFAULT_SMTP_ENCRYPTION}

cat > /opt/wireguard-ui/.env <<EOF
BIND_ADDRESS=${BIND_ADDRESS}
EMAIL_FROM_ADDRESS=${EMAIL_FROM_ADDRESS}
EMAIL_FROM_NAME=${EMAIL_FROM_NAME}
SMTP_HOSTNAME=${SMTP_HOSTNAME}
SMTP_PORT=${SMTP_PORT}
SMTP_USERNAME=${SMTP_USERNAME}
SMTP_PASSWORD=${SMTP_PASSWORD}
SMTP_AUTH_TYPE=${SMTP_AUTH_TYPE}
SMTP_ENCRYPTION=${SMTP_ENCRYPTION}
EOF

echo -e "${GREEN}✔ WireGuard UI 配置已完成${NC}"

echo -e "${YELLOW}[6/8] 配置系统服务...${NC}"
cat > /etc/systemd/system/wireguard-ui.service <<EOF
[Unit]
Description=WireGuard UI Daemon
Wants=network-online.target
After=network-online.target

[Service]
User=root
Group=root
Type=simple
WorkingDirectory=/opt/wireguard-ui
EnvironmentFile=/opt/wireguard-ui/.env
ExecStart=/opt/wireguard-ui/wireguard-ui

[Install]
WantedBy=multi-user.target

EOF

cat > /etc/systemd/system/wgui.service <<EOF
[Unit]
Description=Restart WireGuard
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl restart wg-quick@wg0.service

[Install]
RequiredBy=wgui.path
EOF

cat > /etc/systemd/system/wgui.path <<EOF
[Unit]
Description=Watch /etc/wireguard/wg0.conf for changes

[Path]
PathModified=/etc/wireguard/wg0.conf

[Install]
WantedBy=multi-user.target
EOF

echo -e "${YELLOW}[7/8] 启动所有服务...${NC}"
sleep 1
systemctl daemon-reload
systemctl enable --now wireguard-ui.service
echo -ne "${YELLOW}等待 WireGuard UI 生成配置文件..."${NC}
timeout=30
while [ ! -f /etc/wireguard/wg0.conf ]; do
    if [ $timeout -eq 0 ]; then
        echo -e "\n${RED}✗ 超时：未检测到配置文件生成${NC}"
        echo -e "${YELLOW}请手动访问 Web UI 初始化配置后，再次运行脚本${NC}"
        exit 1
    fi
    echo -n "."
    sleep 1
    ((timeout--))
done
echo -e "\n${GREEN}✔ 配置文件已生成${NC}"
systemctl enable --now wg-quick@wg0.service
systemctl enable --now wgui.{path,service}

if [[ "${disable_firewall,,}" == "y" ]]; then
    echo -e "${YELLOW}[8/8] 配置iptables规则...${NC}"
    sleep 1
    iptables -A FORWARD -i wg0 -o eth0 -j ACCEPT
    iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
    apt-get install -y iptables-persistent
    netfilter-persistent save
else
    echo -e "${YELLOW}[8/8] 跳过iptables规则配置${NC}"
    echo -e "${YELLOW}→ 请手动配置防火墙放行WireGuard流量${NC}"
fi

echo -e "${GREEN}
============================================
安装成功！请访问以下地址管理WireGuard：
http://$(curl -s icanhazip.com):${WGUI_PORT}
默认账号/密码：admin${NC}"
echo -e "${RED}
登录面板后请尽快修改账号密码${NC}"
echo -e "${GREEN}
若配置有误，可重启脚本
或输入vim /opt/wireguard-ui/.env
手动更改并重启服务
============================================${NC}"