#!/bin/bash
set -euo pipefail

# -------------------------------
# 检查 unzip 是否安装
# -------------------------------
if ! command -v unzip &>/dev/null; then
    echo "未检测到 unzip，正在安装..."
    if [ -f /etc/debian_version ]; then
         apt-get update -y && apt-get install -y unzip
    elif [ -f /etc/redhat-release ]; then
         yum install -y unzip
    elif [ -f /etc/alpine-release ]; then
        apk add unzip
    else
        echo "无法自动安装 unzip，请手动安装后重试。"
        exit 1
    fi
else
    echo "unzip 已安装"
fi

# -------------------------------
# 全局配置 - 直接硬编码，确保使用正确的值
# -------------------------------
# 基础URL - 用户提供的具体下载地址
BASE_URL="http://ikuai.zynas.top:8088/easytier/2.4.5"
# 安装目录
INSTALL_DIR="/root/easytier"
# 服务名称
SERVICE_NAME="easytier"
# 全局命令名称 - 改为 ZY
GLOBAL_CMD="/usr/bin/ZY"
# 版本号
EASYTIER_VERSION="v2.4.5"

# -------------------------------
# 定义帮助信息
# -------------------------------
usage() {
    echo "用法: $0 [install|modify|uninstall|update] [username] [hostname]"
    echo "  install   - 全新安装EasyTier服务"
    echo "  modify    - 修改现有配置并重启服务"
    echo "  uninstall - 卸载EasyTier服务并删除文件"
    echo "  update    - 更新EasyTier服务程序文件"
    echo "示例:"
    echo "  $0 install username hostname"
    echo "  $0 modify username hostname"
    echo "  $0 uninstall"
    echo "  $0 update"
    echo "全局命令: ZY (安装后可用)"
    exit 1
}

# -------------------------------
# 获取CPU架构
# -------------------------------
get_arch() {
    local arch=$(uname -m)
    case $arch in
        x86_64) echo "x86_64" ;;
        aarch64) echo "aarch64" ;;
        arm) echo "arm" ;;
        armv7l) echo "armv7" ;;
        armhf) echo "armhf" ;;
        armv7hf) echo "armv7hf" ;;
        mips) echo "mips" ;;
        mipsel) echo "mipsel" ;;
        *) echo "unknown" ;;
    esac
}

# -------------------------------
# 下载并解压EasyTier文件
# -------------------------------
download_and_extract() {
    local arch_name=$1
    local download_url=""
    local extracted_dir_name="easytier-linux-${arch_name}"
    
    # 构建下载URL - 使用用户自己的服务器
    download_url="${BASE_URL}/easytier-linux-${arch_name}-${EASYTIER_VERSION}.zip"
    
    echo "正在下载 EasyTier (${arch_name}) 到 /tmp/easytier.zip..."
    echo "下载地址: ${download_url}"
    
    if ! wget -O /tmp/easytier.zip "${download_url}"; then
        echo "错误: 下载EasyTier失败. 请检查文件是否存在于您的服务器上."
        exit 1
    fi
    
    echo "正在解压文件到 ${INSTALL_DIR}/..."
    mkdir -p "${INSTALL_DIR}"
    unzip -o /tmp/easytier.zip -d "${INSTALL_DIR}/"
    
    if [ $? -ne 0 ]; then
        echo "错误: 解压EasyTier文件失败."
        rm -f /tmp/easytier.zip
        exit 1
    fi
    
    # 移动二级目录中的文件到 ${INSTALL_DIR}/
    if [ -d "${INSTALL_DIR}/${extracted_dir_name}" ]; then
        echo "正在将文件从 ${INSTALL_DIR}/${extracted_dir_name} 移动到 ${INSTALL_DIR}/..."
        mv "${INSTALL_DIR}/${extracted_dir_name}"/* "${INSTALL_DIR}/"
        if [ $? -ne 0 ]; then
            echo "警告: 移动文件失败，请手动检查 ${INSTALL_DIR}/ 目录。"
        fi
        # 删除现在为空的二级目录
        rmdir "${INSTALL_DIR}/${extracted_dir_name}" 2>/dev/null
    else
        echo "警告: 未找到预期的二级目录 ${INSTALL_DIR}/${extracted_dir_name}。请手动检查解压结果。"
    fi
    
    rm -f /tmp/easytier.zip
    chmod +x "${INSTALL_DIR}/easytier-core"
    chmod +x "${INSTALL_DIR}/easytier-cli"
    echo "EasyTier文件下载并解压完成."
}

# -------------------------------
# 安装流程
# -------------------------------
install_service() {
    # 1. 新建文件夹路径为 ${INSTALL_DIR}
    if [ -d "${INSTALL_DIR}" ]; then
        echo "清理旧的安装目录..."
        rm -rf "${INSTALL_DIR}"
    fi
    mkdir -p "${INSTALL_DIR}"
    
    # 2. 根据架构下载并解压文件
    download_and_extract "${ARCH}"
    
    # 3. 创建systemd服务
    echo "创建systemd服务文件..."
    service_content="[Unit]
Description=EasyTier Service
After=network.target syslog.target
Wants=network.target
[Service]
Type=simple
ExecStart=${INSTALL_DIR}/easytier-core -w udp://cfgs.175419.xyz:22020/${USERNAME}  --hostname ${HOSTNAME}
Restart=always
RestartSec=5
LimitNOFILE=1048576
Environment=TOKIO_CONSOLE=1
[Install]
WantedBy=multi-user.target"
    
    echo "$service_content" > /etc/systemd/system/${SERVICE_NAME}.service
    
    # 4. 启动服务
    systemctl daemon-reload
    systemctl enable ${SERVICE_NAME}
    systemctl restart ${SERVICE_NAME}
    
    # 5. 创建全局命令 ZY
    echo "创建全局命令 ${GLOBAL_CMD}..."
    cat > "${GLOBAL_CMD}" << 'EOF'
#!/bin/bash
# EasyTier 全局命令
/root/zy-easytier.sh "$@"
EOF
    chmod +x "${GLOBAL_CMD}"
    
    echo "EasyTier服务已安装并启动！"
    echo "全局命令 ${GLOBAL_CMD} 已创建，可直接使用 ZY 命令管理服务"
    echo "显示运行日志中，请按ctrl+c 取消输出"
    journalctl -f -u easytier.service
}

# -------------------------------
# 修改配置流程
# -------------------------------
modify_config() {
    # 更新服务文件
    service_content="[Unit]
Description=EasyTier Service
After=network.target syslog.target
Wants=network.target
[Service]
Type=simple
ExecStart=${INSTALL_DIR}/easytier-core -w udp://cfgs.175419.xyz:22020/${USERNAME} --hostname ${HOSTNAME}
Restart=always
RestartSec=5
LimitNOFILE=1048576
Environment=TOKIO_CONSOLE=1
[Install]
WantedBy=multi-user.target"
    
    echo "$service_content" > /etc/systemd/system/${SERVICE_NAME}.service
    
    # 重启服务
    systemctl daemon-reload
    systemctl restart easytier
    echo "EasyTier服务配置已更新并重启。查看日志:"
    journalctl -f -u easytier.service
}

# -------------------------------
# 卸载流程
# -------------------------------
uninstall_service() {
    # 1. 停止并禁用服务
    systemctl stop easytier 2>/dev/null
    systemctl disable easytier 2>/dev/null
    systemctl daemon-reload
    systemctl reset-failed
    
    # 2. 删除服务文件
    rm -f /etc/systemd/system/${SERVICE_NAME}.service
    
    # 3. 删除安装文件
    rm -rf "${INSTALL_DIR}"
    
    # 4. 删除全局命令
    rm -f "${GLOBAL_CMD}" 2>/dev/null
    
    echo "EasyTier服务已卸载，相关文件已删除"
}

# -------------------------------
# 更新流程
# -------------------------------
update_service() {
    # 1. 停止服务
    systemctl stop easytier 2>/dev/null
    
    # 2. 删除原来的程序文件
    rm -rf "${INSTALL_DIR}"
    
    # 3. 新建文件夹路径为 ${INSTALL_DIR}
    mkdir -p "${INSTALL_DIR}"
    
    # 4. 根据架构下载并解压新的程序文件
    download_and_extract "${ARCH}"
    
    # 5. 重新启动服务
    systemctl daemon-reload
    systemctl enable easytier
    systemctl restart easytier
    echo "EasyTier服务已更新并重启。查看日志:"
    journalctl -f -u easytier.service
}

# -------------------------------
# 显示菜单
# -------------------------------
show_menu() {
    clear
    echo "====================================="
    echo "        EasyTier 管理菜单"
    echo "====================================="
    echo "1.  安装EasyTier服务"
    echo "2.  修改现有配置"
    echo "3.  卸载EasyTier服务"
    echo "4.  更新EasyTier服务"
    echo "5.  查看运行状态"
    echo "6.  启动EasyTier服务"
    echo "7.  重启EasyTier服务"
    echo "8.  全部卸载（清理所有文件）"
    echo "0.  退出"
    echo "====================================="
    read -p "请选择操作 [0-8]: " choice
}

# -------------------------------
# 查看运行状态
# -------------------------------
show_status() {
    echo "====================================="
    echo "        EasyTier 运行状态"
    echo "====================================="
    echo "服务状态: $(systemctl is-active easytier 2>/dev/null || echo "未运行")"
    echo "开机自启: $(systemctl is-enabled easytier 2>/dev/null && echo "启用" || echo "停用")"
    echo "安装目录: ${INSTALL_DIR}"
    echo "服务文件: /etc/systemd/system/${SERVICE_NAME}.service $([ -f "/etc/systemd/system/${SERVICE_NAME}.service" ] && echo "存在" || echo "不存在")"
    echo "全局命令: ${GLOBAL_CMD} $([ -f "${GLOBAL_CMD}" ] && echo "存在" || echo "不存在")"
    echo "====================================="
    systemctl status easytier 2>/dev/null || echo "服务未安装"
    echo "====================================="
    read -p "按Enter返回菜单..." -n 1
    echo
}

# -------------------------------
# 启动服务
# -------------------------------
start_service() {
    echo "正在启动 EasyTier 服务..."
    systemctl start easytier
    sleep 1
    if systemctl is-active --quiet easytier; then
        echo "✅ 服务启动成功"
    else
        echo "❌ 服务启动失败"
        systemctl status easytier
    fi
    read -p "按Enter返回菜单..." -n 1
    echo
}

# -------------------------------
# 重启服务
# -------------------------------
restart_service() {
    echo "正在重启 EasyTier 服务..."
    systemctl restart easytier
    sleep 1
    if systemctl is-active --quiet easytier; then
        echo "✅ 服务重启成功"
    else
        echo "❌ 服务重启失败"
        systemctl status easytier
    fi
    read -p "按Enter返回菜单..." -n 1
    echo
}

# -------------------------------
# 全部卸载（清理所有文件）
# -------------------------------
full_uninstall() {
    read -p "确定要全部卸载EasyTier并清理所有文件吗？(y/N): " confirm
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        echo "正在执行全部卸载..."
        
        # 停止并禁用服务
        systemctl stop easytier 2>/dev/null || true
        systemctl disable easytier 2>/dev/null || true
        systemctl daemon-reload
        systemctl reset-failed
        
        # 删除服务文件
        rm -f /etc/systemd/system/${SERVICE_NAME}.service
        
        # 删除安装目录
        rm -rf "${INSTALL_DIR}"
        
        # 删除全局命令
        rm -f "${GLOBAL_CMD}" 2>/dev/null || true
        
        # 删除脚本文件
        rm -f "${0}" 2>/dev/null || true
        
        echo "✅ 全部卸载完成，所有文件已清理"
        echo "按Enter退出..."
        read -n 1
        exit 0
    else
        echo "已取消全部卸载"
        read -p "按Enter返回菜单..." -n 1
        echo
    fi
}

# -------------------------------
# 主程序
# -------------------------------

# 获取CPU架构
ARCH=$(get_arch)

# 检查是否通过命令行参数执行
if [ $# -gt 0 ]; then
    # 通过命令行参数执行
    ACTION=$1
    if [ $# -eq 1 ]; then
        if [ "${ACTION}" = "uninstall" ] || [ "${ACTION}" = "update" ]; then
            USERNAME=""
            HOSTNAME=""
        else
            echo "错误: ${ACTION} 操作需要用户名和主机名参数"
            usage
        fi
    elif [ $# -eq 3 ]; then
        USERNAME=$2
        HOSTNAME=$3
    else
        usage
    fi
    
    # 根据参数执行不同操作
    case ${ACTION} in
        install)
            install_service
            ;;
        modify)
            modify_config
            ;;
        uninstall)
            uninstall_service
            ;;
        update)
            update_service
            ;;
        *)
            echo "错误: 未知操作 '${ACTION}'"
            usage
            ;;
    esac
else
    # 显示菜单
    while true; do
        show_menu
        case ${choice} in
            1)  # 安装
                echo "未提供参数，默认执行安装操作"
                read -p "请输入用户名: " USERNAME
                if [ -z "${USERNAME}" ]; then
                    echo "错误: 用户名不能为空"
                    read -p "按Enter返回菜单..." -n 1
                    echo
                    continue
                fi
                read -p "请输入主机名: " HOSTNAME
                if [ -z "${HOSTNAME}" ]; then
                    echo "错误: 主机名不能为空"
                    read -p "按Enter返回菜单..." -n 1
                    echo
                    continue
                fi
                install_service
                ;;
            2)  # 修改配置
                echo "修改现有配置需要用户名和主机名参数"
                read -p "请输入用户名: " USERNAME
                if [ -z "${USERNAME}" ]; then
                    echo "错误: 用户名不能为空"
                    read -p "按Enter返回菜单..." -n 1
                    echo
                    continue
                fi
                read -p "请输入主机名: " HOSTNAME
                if [ -z "${HOSTNAME}" ]; then
                    echo "错误: 主机名不能为空"
                    read -p "按Enter返回菜单..." -n 1
                    echo
                    continue
                fi
                modify_config
                ;;
            3)  # 卸载
                uninstall_service
                read -p "按Enter返回菜单..." -n 1
                echo
                ;;
            4)  # 更新
                update_service
                read -p "按Enter返回菜单..." -n 1
                echo
                ;;
            5)  # 查看状态
                show_status
                ;;
            6)  # 启动服务
                start_service
                ;;
            7)  # 重启服务
                restart_service
                ;;
            8)  # 全部卸载
                full_uninstall
                ;;
            0)  # 退出
                echo "退出EasyTier管理菜单"
                exit 0
                ;;
            *)  # 无效选项
                echo "无效选项！请输入 0-8"
                read -p "按Enter返回菜单..." -n 1
                echo
                ;;
        esac
    done
fi