#!/bin/bash

set -e

URL="https://tuku.wigwy.xyz/down.php/9ad1c8ab453711462bbc38f3715275e9"
BIN="/usr/local/bin/WAF"
SERVICE="/etc/systemd/system/waf.service"

echo "[+] 检查权限..."
if [ "$(id -u)" != "0" ]; then
    echo "[*] 自动提权..."
    exec sudo bash "$0" "$@"
fi

echo "[+] 检查依赖..."
if ! command -v curl >/dev/null 2>&1; then
    echo "[*] 安装 curl..."
    if command -v apt >/dev/null 2>&1; then
        apt update && apt install -y curl
    elif command -v yum >/dev/null 2>&1; then
        yum install -y curl
    elif command -v dnf >/dev/null 2>&1; then
        dnf install -y curl
    else
        echo "[-] 无法自动安装 curl，请手动安装"
        exit 1
    fi
fi

echo "[+] 下载 WAF..."
curl -fsSL "$URL" -o "${BIN}.tmp"

if [ ! -s "${BIN}.tmp" ]; then
    echo "[-] 下载失败"
    exit 1
fi

echo "[+] 安装程序..."
mv "${BIN}.tmp" "$BIN"
chmod +x "$BIN"

echo "[+] 写入 systemd 服务..."
cat > "$SERVICE" <<EOF
[Unit]
Description=Muzi WAF Service
After=network.target

[Service]
Type=simple
ExecStart=$BIN
Restart=always
RestartSec=3
StartLimitInterval=0

# 基础隔离（安全一点）
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

echo "[+] 重新加载 systemd..."
systemctl daemon-reexec
systemctl daemon-reload

echo "[+] 设置开机自启..."
systemctl enable waf

echo "[+] 启动服务..."
systemctl restart waf

echo "[+] 检查状态..."
systemctl status waf --no-pager || true

echo ""
echo "===================================="
echo "[+] 安装完成！"
echo "[+] 查看状态: systemctl status waf"
echo "[+] 查看日志: journalctl -u waf -f"
echo "===================================="