#!/bin/bash
# 核心配色
G="\033[1;32m"  # 亮绿
R="\033[1;31m"  # 亮红
Y="\033[1;33m"  # 亮黄
C="\033[1;36m"  # 亮青
B="\033[1;34m"  # 亮蓝
F="\033[0m"

# 检查并安装必要工具
check_tools() {
    if ! command -v lsof >/dev/null 2>&1; then
        echo -e "${Y}正在安装必要工具 lsof...${F}"
        apt update && apt install lsof -y >/dev/null 2>&1 || yum install lsof -y >/dev/null 2>&1
    fi
}

# 1. 环境修复/安装
install_realm() {
    clear && echo -e "${G}◈ 正在初始化并修复 Realm 环境...${F}"
    check_tools
    mkdir -p /etc/realm
    cat > /etc/sysctl.d/99-realm.conf <<EOT
net.ipv4.ip_forward = 1
net.core.default_qdisc = cake
net.ipv4.tcp_congestion_control = bbr
EOT
    sysctl -p /etc/sysctl.d/99-realm.conf >/dev/null 2>&1
    
    wget -N https://github.com/zhboner/realm/releases/latest/download/realm-x86_64-unknown-linux-gnu.tar.gz
    tar -xvf realm-x86_64-unknown-linux-gnu.tar.gz && chmod +x realm && mv realm /usr/bin/realm
    rm -f realm-x86_64-unknown-linux-gnu.tar.gz
    
    cat > /etc/systemd/system/realm.service <<EOT
[Unit]
Description=realm
After=network-online.target

[Service]
Type=simple
User=root
Restart=on-failure
RestartSec=5s
WorkingDirectory=/etc/realm
ExecStart=/usr/bin/realm -c /etc/realm/config.toml

[Install]
WantedBy=multi-user.target
EOT
    systemctl daemon-reload
    systemctl enable realm
    echo -e "[network]\nno_delay = true\nkeepalive = 30" > /etc/realm/config.toml
    echo -e "${G}✔ 环境修复完成！${F}"
    sleep 2
}

# 2. 端口清理函数
release_port() {
    local port=$1
    if [ -z "$port" ]; then
        read -p "请输入要释放的端口号: " port
    fi
    
    local pid=$(lsof -t -i:"$port")
    if [ -z "$pid" ]; then
        echo -e "${Y}ℹ 端口 $port 未被占用。${F}"
    else
        echo -e "${R}⚠ 发现端口 $port 被进程 $pid 占用，正在强制释放...${F}"
        kill -9 $pid
        echo -e "${G}✔ 端口 $port 已成功释放！${F}"
    fi
}

# 3. 规则添加 (集成自动清理逻辑)
add_rule() {
    clear && echo -e "${C}◈ 添加新转发规则 (自动同步 TCP+UDP)${F}"
    check_tools
    read -p "  输入本机监听端口: " lp
    
    # 自动检测占用
    if lsof -i:"$lp" >/dev/null 2>&1; then
        echo -e "${R}× 警告：端口 $lp 已被占用！${F}"
        read -p "  是否强制释放该端口并继续？(y/n): " confirm
        if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
            release_port "$lp"
        else
            return
        fi
    fi

    read -p "  输入远程转发 IP : " rip
    read -p "  输入远程转发端口: " rp
    
    CONF="/etc/realm/config.toml"
    if grep -q ":$lp\"" "$CONF"; then
        echo -e "${R}× 错误：端口 $lp 规则已存在！${F}"
    else
        echo -e "\n[[endpoints]]\nlisten = \"0.0.0.0:$lp\"\nremote = \"tcp+udp://$rip:$rp\"" >> "$CONF"
        iptables -I INPUT -p tcp --dport $lp -j ACCEPT
        iptables -I INPUT -p udp --dport $lp -j ACCEPT
        systemctl restart realm && echo -e "${G}✔ 规则启用成功！${F}"
    fi
    read -p "按回车返回..."
}

# 4. 查看清单
show_rules() {
    clear && echo -e "${C}📜 当前转发规则仪表盘${F}"
    echo -e "${B}----------------------------------------${F}"
    CONF="/etc/realm/config.toml"
    if [ ! -f "$CONF" ] || ! grep -q "endpoints" "$CONF"; then
        echo -e "${R}  ( 暂无有效转发规则 )${F}"
    else
        grep -E "listen =|remote =" "$CONF" | sed 'N;s/\n/ /' | while read -r line; do
            l_port=$(echo $line | awk -F'"' '{print $2}' | awk -F':' '{print $NF}')
            r_addr=$(echo $line | awk -F'"' '{print $4}')
            echo -e "  ${Y}监听 ${l_port}${F}  ${G}➔${F}  ${C}${r_addr}${F}"
        done
    fi
    echo -e "${B}----------------------------------------${F}"
    read -p "按回车返回..."
}

# 主菜单
while true; do
    clear
    echo -e "${C}┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓${F}"
    echo -e "${C}┃      ${G}Realm 网络管理 PRO${F}      ${C}┃${F}"
    echo -e "${C}┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛${F}"
    echo -e "  ${Y}1.${F} 安装/修复 Realm 环境"
    echo -e "  ${Y}2.${F} 添加转发规则 (含占用检测)"
    echo -e "  ${Y}3.${F} 查看规则清单"
    echo -e "  ${B}4. 强制释放指定端口${F}"
    echo -e "  ${R}5. 清空重置规则${F}"
    echo -e "  ${B}0. 退出系统${F}"
    echo -e "${C}------------------------------${F}"
    read -p "请输入选项: " opt
    case $opt in
        1) install_realm ;;
        2) add_rule ;;
        3) show_rules ;;
        4) release_port ;;
        5) rm -f /etc/realm/config.toml
           echo -e "[network]\nno_delay = true\nkeepalive = 30" > /etc/realm/config.toml
           systemctl restart realm
           echo -e "${R}>>> 规则已重置并清空！${F}"; sleep 1 ;;
        0) exit 0 ;;
    esac
done