#!/bin/bash

# ==========================================
# GOST v3 多节点轮询转发一键管理脚本
# ==========================================

CONFIG_PATH="/etc/gost/config.yaml"
SERVICE_PATH="/etc/systemd/system/gost.service"
GOST_BIN="/usr/local/bin/gost"
SHORTCUT_BIN="/usr/local/bin/go"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
SKYBLUE='\033[0;36m'
PLAIN='\033[0m'

# 检查 Root 权限
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}错误：必须使用 root 权限运行此脚本！${PLAIN}"
        exit 1
    fi
}

# 检测 GOST 是否已安装
check_installed() {
    if [[ -f "$GOST_BIN" ]] && gost -V &>/dev/null; then
        return 0
    else
        return 1
    fi
}

# 创建 go 软链接快捷命令
create_shortcut() {
    if [[ ! -f "$SHORTCUT_BIN" ]] || [[ $(readlink -f "$SHORTCUT_BIN") != "/root/gost_manager.sh" ]]; then
        rm -f "$SHORTCUT_BIN" 2>/dev/null
        ln -s /root/gost_manager.sh "$SHORTCUT_BIN"
        chmod +x "$SHORTCUT_BIN"
    fi
}

# 1. 安装 GOST v3 核心环境
install_gost() {
    echo -e "${SKYBLUE}>>> 检查并安装系统依赖 (python3, curl, tar)...${PLAIN}"
    if command -v apt-get &>/dev/null; then
        apt-get update -y && apt-get install -y python3 curl tar
    elif command -v yum &>/dev/null; then
        yum install -y python3 curl tar
    fi

    if check_installed; then
        echo -e "${GREEN}>>> 检测到 GOST 已安装，版本为：$(gost -V)${PLAIN}"
        return
    fi

    echo -e "${SKYBLUE}>>> 开始下载并安装 GOST v3 (v3.3.0 稳定版)...${PLAIN}"
    
    DOWNLOAD_URL="https://file.5itv.cn/sh/gostv3/gost_3.3.0_linux_amd64.tar.gz"
    
    cd /tmp
    curl -sL "$DOWNLOAD_URL" -o gost.tar.gz
    if [[ $? -ne 0 ]] || [[ ! -f gost.tar.gz ]]; then
        echo -e "${YELLOW}>>> 镜像源下载失败，尝试官方直连...${PLAIN}"
        curl -sL "https://github.com/go-gost/gost/releases/download/v3.3.0/gost_3.3.0_linux_amd64.tar.gz" -o gost.tar.gz
    fi

    tar -zxvf gost.tar.gz
    mv gost "$GOST_BIN"
    chmod +x "$GOST_BIN"
    rm -rf gost.tar.gz README* LICENSE*

    if check_installed; then
        echo -e "${GREEN}>>> GOST v3 安装成功！${PLAIN}"
    else
        echo -e "${RED}>>> GOST v3 安装失败，请检查网络或配置！${PLAIN}"
        exit 1
    fi
}

# 2. 生成多节点轮询配置文件
generate_config() {
    mkdir -p /etc/gost

    echo -e "\n${SKYBLUE}------------------------------------------------${PLAIN}"
    echo -e "${YELLOW}配置转发规则（端口段：11011 - 11034）${PLAIN}"
    echo -e "${SKYBLUE}------------------------------------------------${PLAIN}"
    echo -e "请输入所有目标【腾讯锐驰 VPS】的 IP 地址。"
    echo -e "如果有多个 IP，请用${GREEN}半角逗号或空格${PLAIN}隔开（例如: 42.194.206.86, 1.2.3.4）:"
    read -p "腾讯锐驰 IP 列表: " raw_ips

    if [[ -z "$raw_ips" ]]; then
        echo -e "${RED}错误：必须输入至少一个腾讯锐驰 IP！${PLAIN}"
        return 1
    fi

    python3 -c "
import re

raw_input = '''$raw_ips'''
ips = re.findall(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}', raw_input)

if not ips:
    print('${RED}未能解析出有效的 IP 地址，请检查输入！${PLAIN}')
    exit(1)

config = 'services:\n'
for i in range(24):
    p_in = 11011 + i
    config += f'  - name: s-{p_in}\n    addr: :{p_in}\n    handler:\n      type: tcp\n    listener:\n      type: tcp\n    forwarder:\n      selector:\n        strategy: roundrobin\n        maxFails: 3\n        failTimeout: 10s\n      nodes:\n'
    for idx, ip in enumerate(ips):
        config += f'        - name: node-{p_in}-{idx}\n          addr: {ip}:{p_in}\n'

with open('$CONFIG_PATH', 'w') as f:
    f.write(config)

print('\n${GREEN}✅ 配置文件生成成功！已绑定 IP 列表:${PLAIN}')
for ip in ips:
    print(f'   - {ip}')
"
    if [[ $? -ne 0 ]]; then
        return 1
    fi
}

# 3. 配置 Systemd 守护服务
setup_systemd() {
    cat << 'SERVICE' > "$SERVICE_PATH"
[Unit]
Description=GOST v3 Round-Robin Tunnel Service
After=network.target wpa_supplicant.service

[Service]
Type=simple
ExecStart=/usr/local/bin/gost -C /etc/gost/config.yaml
Restart=always
RestartSec=3
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
SERVICE

    systemctl daemon-reload
    systemctl enable gost &>/dev/null
    systemctl restart gost
    echo -e "${GREEN}>>> GOST Systemd 守护服务已配置并成功启动/开机自启！${PLAIN}"
}

# 4. 彻底卸载函数
uninstall_gost() {
    echo -e "\n${RED}================ 卸载 GOST =================${PLAIN}"
    read -p "确定要彻底卸载 GOST 及其所有配置文件吗？[y/N]: " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo -e "${YELLOW}已取消卸载。${PLAIN}"
        return
    fi

    echo -e "${SKYBLUE}>>> 正在停止并禁用 GOST 服务...${PLAIN}"
    systemctl stop gost &>/dev/null
    systemctl disable gost &>/dev/null
    rm -f "$SERVICE_PATH"
    systemctl daemon-reload

    echo -e "${SKYBLUE}>>> 正在清理程序二进制与配置文件...${PLAIN}"
    rm -f "$GOST_BIN"
    rm -rf /etc/gost
    rm -f "$SHORTCUT_BIN"
    rm -f /root/gost_manager.sh

    echo -e "${GREEN}>>> GOST 及其一键管理脚本已彻底完全卸载！${PLAIN}\n"
    exit 0
}

# 查看实时运行日志
view_logs() {
    echo -e "${SKYBLUE}>>> 正在调取 GOST 实时日志 (按 Ctrl + C 退出查看)...${PLAIN}\n"
    journalctl -u gost -f -n 50
}

# 状态与规则计数头部展示
show_status_header() {
    echo -e "${GREEN}=== 当前状态 ===${PLAIN}"
    
    # 1. 运行状态判断
    if systemctl is-active --quiet gost 2>/dev/null; then
        STATUS_STR="${GREEN}● 运行中${PLAIN}"
    elif check_installed; then
        STATUS_STR="${RED}● 已停止${PLAIN}"
    else
        STATUS_STR="${YELLOW}● 未安装${PLAIN}"
    fi
    echo -e "服务状态: $STATUS_STR"

    # 2. 规则数量解析
    if [[ -f "$CONFIG_PATH" ]]; then
        TOTAL_RULES=$(grep -c "name: s-" "$CONFIG_PATH" 2>/dev/null || echo 0)
        if systemctl is-active --quiet gost 2>/dev/null; then
            ACTIVE_RULES=$TOTAL_RULES
            INACTIVE_RULES=0
        else
            ACTIVE_RULES=0
            INACTIVE_RULES=$TOTAL_RULES
        fi
        echo -e "配置模式: 多规则模式 ($ACTIVE_RULES 启用 / $INACTIVE_RULES 禁用 / 共 $TOTAL_RULES 个)"
    else
        echo -e "配置模式: 未配置转发规则"
    fi
}

# 一键安装流程
full_install() {
    install_gost
    generate_config
    if [[ $? -eq 0 ]]; then
        setup_systemd
        echo -e "${GREEN}>>> 提示：后续只需在终端输入【go】即可随时调出此管理面板！${PLAIN}\n"
    fi
}

# 交互式主菜单
show_menu() {
    create_shortcut
    clear
    show_status_header
    echo -e "${GREEN}================================================${PLAIN}"
    echo -e "${GREEN}      GOST v3 四层轮询转发一键管理脚本          ${PLAIN}"
    echo -e "${GREEN}================================================${PLAIN}"
    echo -e " 1. ${SKYBLUE}完整安装 / 重新配置转发${PLAIN}"
    echo -e " 2. ${SKYBLUE}修改腾讯锐驰 IP 列表 (重构轮询规则)${PLAIN}"
    echo -e " 3. ${GREEN}重启 GOST 服务${PLAIN}"
    echo -e " 4. ${YELLOW}停止 GOST 服务${PLAIN}"
    echo -e " 5. ${SKYBLUE}查看服务运行状态与端口详情${PLAIN}"
    echo -e " 6. ${SKYBLUE}查看实时日志 (journalctl)${PLAIN}"
    echo -e " 7. ${RED}彻底卸载 GOST 服务与脚本${PLAIN}"
    echo -e " 0. 退出脚本"
    echo -e "${GREEN}================================================${PLAIN}"
    read -p "请输入选项 [0-7]: " choice

    case "$choice" in
        1)
            full_install
            ;;
        2)
            generate_config
            if [[ $? -eq 0 ]]; then
                systemctl restart gost
                echo -e "${GREEN}>>> 规则已更新并成功重启服务！${PLAIN}"
            fi
            ;;
        3)
            systemctl restart gost
            echo -e "${GREEN}>>> GOST 服务已重新启动！${PLAIN}"
            ;;
        4)
            systemctl stop gost
            echo -e "${YELLOW}>>> GOST 服务已停止！${PLAIN}"
            ;;
        5)
            echo -e "\n${SKYBLUE}================ 端口监听检测 ================${PLAIN}"
            LISTEN_COUNT=$(ss -tuln | grep -E "11011|11012|11013" | wc -l)
            if [[ $LISTEN_COUNT -gt 0 ]]; then
                echo -e "端口监听: ${GREEN}正常 (11011-11034 已在监听)${PLAIN}"
            else
                echo -e "端口监听: ${YELLOW}未检测到 11011+ 端口监听${PLAIN}"
            fi
            echo -e "${SKYBLUE}==============================================${PLAIN}\n"
            ;;
        6)
            view_logs
            ;;
        7)
            uninstall_gost
            ;;
        0)
            exit 0
            ;;
        *)
            echo -e "${RED}无效选项，请重新输入！${PLAIN}"
            ;;
    esac
}

check_root
show_menu
