#!/bin/bash

# 默认配置
DEFAULT_INSTALL_DIR="/opt/cfech"
BIN_NAME="ech-workers"
SERVICE_NAME="ech-workers"
GITHUB_REPO="byJoey/ech-wk"
PROXY_PREFIX="https://github.govless.pp.ua/"

# 检查 root 权限
[[ $EUID -ne 0 ]] && echo "错误: 请使用 sudo 运行此脚本" && exit 1

# 1. 设置安装路径
setup_path() {
    echo ">>> 步骤 1: 设置安装路径"
    read -p "请输入安装目录 [默认: $DEFAULT_INSTALL_DIR]: " custom_dir
    INSTALL_DIR=${custom_dir:-$DEFAULT_INSTALL_DIR}
    CONF_FILE="$INSTALL_DIR/ech.json"
    SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service"
    echo "路径设定为: $INSTALL_DIR"
}

# 2. 安装必要依赖
install_deps() {
    echo ">>> 步骤 2: 检查并安装依赖工具 (curl, jq, tar)..."
    for pkg in curl jq tar; do
        if ! command -v $pkg >/dev/null 2>&1; then
            echo "正在安装 $pkg..."
            if command -v apt-get >/dev/null 2>&1; then
                apt-get update && apt-get install -y $pkg
            else
                yum install -y $pkg
            fi
        fi
    done
}

# 3. 下载并安装二进制文件 (使用代理)
install_bin() {
    echo ">>> 步骤 3: 下载最新版程序文件..."
    mkdir -p "$INSTALL_DIR"
    cd "$INSTALL_DIR" || exit 1
    
    # 架构检测
    ARCH=$(uname -m)
    case "$ARCH" in
        x86_64)  SUFFIX="linux-amd64" ;;
        aarch64) SUFFIX="linux-arm64" ;;
        *) echo "暂不支持的架构: $ARCH"; exit 1 ;;
    esac
    
    # 获取 GitHub 最新 Release 地址
    RAW_URL=$(curl -s https://api.github.com/repos/$GITHUB_REPO/releases/latest | \
          jq -r ".assets[] | select(.name | contains(\"$SUFFIX\")) | .browser_download_url" | head -n 1)
    
    if [[ -z "$RAW_URL" || "$RAW_URL" == "null" ]]; then
        echo "错误: 无法获取下载链接，请检查网络。"
        exit 1
    fi

    # 拼接加速代理前缀
    URL="${PROXY_PREFIX}${RAW_URL}"

    echo "正在通过加速通道下载: $URL"
    curl -L -o "ech-workers.tar.gz" "$URL"
    
    if [[ $? -ne 0 ]]; then
        echo "下载失败，请检查网络或加速代理状态。"
        exit 1
    fi

    tar -zxf "ech-workers.tar.gz"
    
    # 清理并规范化命名
    EXTRACTED_BIN=$(find . -name "ech-workers*" -type f -executable | head -n 1)
    mv "$EXTRACTED_BIN" "$BIN_NAME"
    chmod +x "$BIN_NAME"
    rm -f "ech-workers.tar.gz"
    echo "程序已安装至: $INSTALL_DIR/$BIN_NAME"
}

# 4. 交互式创建配置
check_and_create_config() {
    echo ">>> 步骤 4: 检查并创建配置文件..."
    if [[ -f "$CONF_FILE" ]]; then
        read -p "检测到已存在配置文件，是否重新配置？[y/N]: " reconf
        [[ "$reconf" != "y" && "$reconf" != "Y" ]] && return
    fi

    echo "--- 请输入以下配置信息 ---"
    # 服务端地址 (必需)
    read -p "服务端地址 (f) [例如: worker.xxx.dev:443]: " f_addr
    while [[ -z "$f_addr" ]]; do read -p "地址不能为空，请重新输入: " f_addr; done

    # Token (必需)
    read -p "身份验证 Token: " token_val
    while [[ -z "$token_val" ]]; do read -p "Token 不能为空，请重新输入: " token_val; done

    # 本地监听 (可选)
    read -p "本地监听地址 [默认 127.0.0.1:30000]: " l_addr
    l_addr=${l_addr:-"127.0.0.1:30000"}

    # 生成 JSON 文件
    cat <<EOF > "$CONF_FILE"
{
  "f": "$f_addr",
  "l": "$l_addr",
  "token": "$token_val",
  "routing": "bypass_cn",
  "dns": "dns.alidns.com/dns-query",
  "ech": "cloudflare-ech.com"
}
EOF
    echo "配置文件已生成: $CONF_FILE"
}

# 5. 生成 Systemd 服务 (启动时动态读取 JSON 参数)
setup_service() {
    echo ">>> 步骤 5: 注册并启动 Systemd 服务..."
    
    # 使用 sh -c 让 ExecStart 在启动瞬间通过 jq 抓取 JSON 值
    cat <<EOF > "$SERVICE_FILE"
[Unit]
Description=ECH Workers Proxy Client
After=network.target

[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR
ExecStart=/bin/sh -c 'exec $INSTALL_DIR/$BIN_NAME \\
    -f \$(jq -r ".f" $CONF_FILE) \\
    -l \$(jq -r ".l // \\"127.0.0.1:30000\\"" $CONF_FILE) \\
    -token \$(jq -r ".token" $CONF_FILE) \\
    -routing \$(jq -r ".routing // \\"global\\"" $CONF_FILE)'
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME"
    systemctl restart "$SERVICE_NAME"
    
    echo "------------------------------------------------"
    echo "部署完成！"
    echo "安装目录: $INSTALL_DIR"
    echo "配置文件: $CONF_FILE"
    echo ""
    echo "管理命令:"
    echo "查看日志: sudo journalctl -u $SERVICE_NAME -f"
    echo "重启服务: sudo systemctl restart $SERVICE_NAME"
    echo "------------------------------------------------"
}

# 入口控制
case "$1" in
    install)
        setup_path
        install_deps
        install_bin
        check_and_create_config
        setup_service
        ;;
    update)
        # 自动识别安装路径
        if [[ -f /etc/systemd/system/$SERVICE_NAME.service ]]; then
            INSTALL_DIR=$(grep "WorkingDirectory" /etc/systemd/system/$SERVICE_NAME.service | cut -d'=' -f2)
        else
            INSTALL_DIR=$DEFAULT_INSTALL_DIR
        fi
        install_bin
        systemctl restart "$SERVICE_NAME"
        echo "程序已更新并重启。"
        ;;
    log)
        journalctl -u "$SERVICE_NAME" -f
        ;;
    uninstall)
        systemctl stop "$SERVICE_NAME"
        systemctl disable "$SERVICE_NAME"
        rm -f "/etc/systemd/system/$SERVICE_NAME.service"
        echo "服务已成功卸载。"
        ;;
    *)
        echo "用法: $0 {install|update|log|uninstall}"
        exit 1
esac