#!/bin/bash

GREEN="\033[32m"
RESET="\033[0m"

if [ "$(id -u)" -ne 0 ]; then
    echo "请用 root 身份运行这个脚本"
    exit 1
fi

echo -n "请输入[80端口]队列 100 的窗口大小 (-w 的值)："
read WINDOW_100
if ! [[ "$WINDOW_100" =~ ^[0-9]+$ ]]; then
    echo "窗口大小必须是数字"
    exit 1
fi

echo -n "请输入[443端口]队列 101 的窗口大小 (-w 的值)："
read WINDOW_101
if ! [[ "$WINDOW_101" =~ ^[0-9]+$ ]]; then
    echo "窗口大小必须是数字"
    exit 1
fi

echo -e "队列 100 的窗口大小设为: ${GREEN}${WINDOW_100}${RESET}"
echo -e "队列 101 的窗口大小设为: ${GREEN}${WINDOW_101}${RESET}"

#cat << EOF > /etc/apt/sources.list
#deb http://mirrors.cloud.aliyuncs.com/debian/ bullseye main contrib non-free
#deb http://mirrors.cloud.aliyuncs.com/debian/ bullseye-updates main contrib non-free
#deb http://mirrors.cloud.aliyuncs.com/debian/ bullseye-proposed-updates main non-free contrib
#deb-src http://mirrors.cloud.aliyuncs.com/debian/ bullseye-updates main contrib non-free
#deb-src http://mirrors.cloud.aliyuncs.com/debian/ bullseye main contrib non-free
#deb-src http://mirrors.cloud.aliyuncs.com/debian/ bullseye-proposed-updates main contrib non-free
#deb http://mirrors.cloud.aliyuncs.com/debian-security/ bullseye-security main non-free contrib
#deb-src http://mirrors.cloud.aliyuncs.com/debian-security/ bullseye-security main non-free contrib
#EOF

echo -e "${GREEN}正在更新系统...${RESET}"
apt-get update -y

echo -e "${GREEN}正在安装依赖...${RESET}"
apt-get install -y \
    libnetfilter-queue-dev \
    libmnl-dev \
    iptables \
    build-essential \
    supervisor \
    iptables-persistent \
    wget

cat << EOF > /etc/iptables/rules.v4
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A OUTPUT -p tcp -m tcp --sport 443 --tcp-flags FIN,SYN,RST,PSH,ACK SYN,ACK -j NFQUEUE --queue-num 101
-A OUTPUT -p tcp -m tcp --sport 80  --tcp-flags FIN,SYN,RST,PSH,ACK SYN,ACK -j NFQUEUE --queue-num 100
COMMIT
EOF

iptables-restore < /etc/iptables/rules.v4

cat << EOF > /etc/supervisor/conf.d/geneva.conf
[program:geneva-q100]
process_name=%(program_name)s
command=/opt/geneva/geneva -q 100 -w ${WINDOW_100}
directory=/opt/
user=root
autostart=true
autorestart=true
priority=10
stdout_logfile=/dev/null
stderr_logfile=/dev/null

[program:geneva-q101]
process_name=%(program_name)s
command=/opt/geneva/geneva -q 101 -w ${WINDOW_101}
directory=/opt/
user=root
autostart=true
autorestart=true
priority=20
stdout_logfile=/dev/null
stderr_logfile=/dev/null
EOF

echo -e "${GREEN}正在下载 geneva 可执行文件...${RESET}"
mkdir -p /opt/geneva
wget https://file.xf.kg/geneva/geneva -O /opt/geneva/geneva

echo -e "${GREEN}正在设置执行权限...${RESET}"
chmod +x /opt/geneva/geneva

if command -v systemctl >/dev/null 2>&1; then
    systemctl enable --now supervisor
else
    service supervisor start || true
fi

supervisorctl reread
supervisorctl update

echo -e "${GREEN}安装完成。${RESET}"
echo -e "${GREEN}队列 100 使用: -w ${WINDOW_100}${RESET}"
echo -e "${GREEN}队列 101 使用: -w ${WINDOW_101}${RESET}"
echo -e "${GREEN}NFQUEUE 规则已写入 /etc/iptables/rules.v4 并立即生效${RESET}"