# shellcheck disable=SC2148
# shellcheck disable=SC1091
. script/common.sh >&/dev/null
. script/fastclash.sh >&/dev/null
. script/download.sh >&/dev/null

_valid_env

[ -d "$CLASH_BASE_DIR" ] && _error_quit "请先执行卸载脚本,以清除安装路径：$CLASH_BASE_DIR"

# 标记安装是否成功
INSTALL_SUCCESS=0
CONFIG_SUCCESS=0

# ===== 第一步：下载必需资源 =====
echo "=========================================="
_okcat '[STEP]' "第一步：下载必需资源"
echo "=========================================="

if _download_required_resources; then
    _okcat '[SUCCESS]' "所有必需资源下载成功"
    INSTALL_SUCCESS=1
else
    _failcat '[FAIL]' "资源下载失败，请检查网络连接"
    _error_quit "[ERROR] 安装失败：无法下载必需资源"
fi

# ===== 第二步：安装内核和工具 =====
echo ""
echo "=========================================="
_okcat '[STEP]' "第二步：安装内核和工具"
echo "=========================================="

_get_kernel

# 安装内核
/usr/bin/install -D <(gzip -dc "$ZIP_KERNEL") "${RESOURCES_BIN_DIR}/$BIN_KERNEL_NAME" || {
    _error_quit "[ERROR] 内核安装失败"
}

# 解压工具
tar -xf "$ZIP_SUBCONVERTER" -C "$RESOURCES_BIN_DIR" || {
    _error_quit "[ERROR] subconverter 解压失败"
}
tar -xf "$ZIP_YQ" -C "${RESOURCES_BIN_DIR}" || {
    _error_quit "[ERROR] yq 解压失败"
}
# shellcheck disable=SC2086
/bin/mv -f ${RESOURCES_BIN_DIR}/yq_* "${RESOURCES_BIN_DIR}/yq"

# 设置二进制文件路径
_set_bin "$RESOURCES_BIN_DIR"
_okcat '[OK]' "内核和工具安装完成"

# ===== 第三步：配置 Clash（可选） =====
echo ""
echo "=========================================="
_okcat '[STEP]' "第三步：配置 Clash（可选）"
echo "=========================================="

# 检查是否已有配置
if _valid_config "$RESOURCES_CONFIG"; then
    _okcat '[OK]' '发现已有配置文件，跳过配置下载'
    url=""
    CONFIG_SUCCESS=1
else
    # 询问是否需要配置订阅
    echo ""
    echo "是否需要配置订阅链接？"
    echo "1) 是 - 输入订阅链接"
    echo "2) 否 - 稍后手动配置"
    echo -n "请选择 (1/2) [1]: "
    read -r choice

    case "$choice" in
        2|"N"|"n"|"NO"|"no"|"No")
            _okcat '[INFO]' "跳过配置，您可以稍后手动配置"
            url=""
            # 创建一个最小配置文件
            cat > "$RESOURCES_CONFIG" << 'EOF'
# Clash 配置文件
# 请手动修改或使用 clash update 命令更新订阅

port: 7890
socks-port: 7891
mixed-port: 7892
allow-lan: true
mode: rule
log-level: info
external-controller: 0.0.0.0:9090
dns:
  enable: true
  enhanced-mode: fake-ip
  fake-ip-range: 198.18.0.1/16
  nameserver:
    - 114.114.114.114
    - 8.8.8.8
    - tls://dns.google:853
proxy-groups: []
rules: []
EOF
            _okcat '[OK]' '已创建默认配置文件'
            CONFIG_SUCCESS=1
            ;;
        *)
            # 配置订阅
            echo ""
            # 检查是否通过环境变量传递了订阅链接
            if [ -n "$CLASH_SUBSCRIPTION_URL" ]; then
                url="$CLASH_SUBSCRIPTION_URL"
                _okcat '[INFO]' "使用环境变量中的订阅：$url"
            else
                echo -n "$(_okcat '[INFO]' '请输入订阅链接：')"
                read -r url
            fi

            if [ -n "$url" ]; then
                _okcat '[INFO]' '正在下载配置...'
                if _download_config "$RESOURCES_CONFIG" "$url"; then
                    if _valid_config "$RESOURCES_CONFIG"; then
                        _okcat '[SUCCESS]' '配置下载并验证成功'
                        CONFIG_SUCCESS=1
                    else
                        _failcat '[WARNING]' "配置验证失败，请检查：$RESOURCES_CONFIG"
                        _failcat '[INFO]' "转换日志：$BIN_SUBCONVERTER_LOG"
                        _failcat '[INFO]' "您可以使用 clash update 命令重新配置"
                    fi
                else
                    _failcat '[FAIL]' "配置下载失败（可能是网络问题或链接无效）"
                    _failcat '[INFO]' "错误原因：SSL 连接失败或连接被重置通常是网络问题"
                    _failcat '[INFO]' "建议："
                    echo "  1. 检查网络连接"
                    echo "  2. 尝试其他订阅链接"
                    echo "  3. 稍后使用 clash update 命令重新配置"
                    echo ""
                    # 创建最小配置
                    cat > "$RESOURCES_CONFIG" << 'EOF'
# Clash 配置文件（待更新）
# 请使用 clash update 命令更新订阅

port: 7890
socks-port: 7891
mixed-port: 7892
allow-lan: true
mode: rule
log-level: info
external-controller: 0.0.0.0:9090
dns:
  enable: true
  enhanced-mode: fake-ip
  fake-ip-range: 198.18.0.1/16
  nameserver:
    - 114.114.114.114
    - 8.8.8.8
proxy-groups: []
rules: []
EOF
                    _okcat '[INFO]' '已创建默认配置文件'
                    CONFIG_SUCCESS=0
                fi
            fi
            ;;
    esac
fi

# 保存订阅链接（如果有）
: "${url:=}"

# ===== 第四步：部署到系统 =====
echo ""
echo "=========================================="
_okcat '[STEP]' "第四步：部署到系统"
echo "=========================================="

_sudo mkdir -p "$CLASH_BASE_DIR"
echo "$url" | _sudo tee "$CLASH_CONFIG_URL" >&/dev/null

# 复制脚本文件
_sudo /bin/cp -rf "$SCRIPT_BASE_DIR" "$CLASH_BASE_DIR"

# 复制资源文件
for resource in "$RESOURCES_BASE_DIR"/*; do
    name=$(basename "$resource")
    case "$name" in
        zip|png) continue ;;
        *) _sudo /bin/cp -rf "$resource" "$CLASH_BASE_DIR" ;;
    esac
done

# 解压 UI
_sudo tar -xf "$ZIP_UI" -C "$CLASH_BASE_DIR"

# 设置环境变量
_set_rc
_set_bin

# 创建 systemd 服务
_sudo mkdir -p "$CLASH_SERVICE_DIR"

if [[ "$FASTCLASH_INSTALL_SCOPE" = "system" ]]; then
    target_unit='multi-user.target'
else
    target_unit='default.target'
fi

_sudo tee "${CLASH_SERVICE_DIR}/${BIN_KERNEL_NAME}.service" >/dev/null <<EOF
[Unit]
Description=$BIN_KERNEL_NAME Daemon, A[nother] Clash Kernel.

[Service]
Type=simple
Restart=always
ExecStart=${BIN_KERNEL} -d ${CLASH_BASE_DIR} -f ${CLASH_CONFIG_RUNTIME}

[Install]
WantedBy=${target_unit}
EOF

_systemctl daemon-reload
if _systemctl enable "$BIN_KERNEL_NAME" >&/dev/null; then
    _okcat '[OK]' "已设置开机自启"
else
    _failcat '[FAIL]' "设置自启失败"
fi

# 创建 clash 命令包装器
wrapper_path="${CLASH_BIN_DIR}/clash"
_sudo mkdir -p "$(dirname "$wrapper_path")"
_sudo tee "$wrapper_path" >/dev/null <<EOF
#!/bin/bash
export FASTCLASH_INSTALL_SCOPE="${FASTCLASH_INSTALL_SCOPE}"
export FASTCLASH_SYSTEM_MODE="${FASTCLASH_SYSTEM_MODE}"
source "${CLASH_SCRIPT_DIR}/common.sh"
source "${CLASH_SCRIPT_DIR}/fastclash.sh"
clash "\$@"
EOF
_sudo chmod +x "$wrapper_path"

# 合并配置并重启（如果有配置）
if [ "$CONFIG_SUCCESS" = "1" ] && [ -f "$RESOURCES_CONFIG" ]; then
    _merge_config_restart
fi

# 显示安装结果
echo ""
echo "=========================================="
echo "              安装完成！"
echo "=========================================="

# 安装状态总结
echo ""
echo "[INFO] 安装状态："
echo "  [OK] fastclash 安装：成功"
if [ "$CONFIG_SUCCESS" = "1" ]; then
    echo "  [OK] 配置文件：成功"
else
    echo "  [WARNING] 配置文件：失败（但这不影响 fastclash 使用）"
fi

echo ""
echo "[INFO] 后续使用说明："
echo ""
echo "基本命令："
echo "  clash on          # 开启代理"
echo "  clash off         # 关闭代理"
echo "  clash status      # 查看状态"
echo "  clash ui          # 打开 Web 控制台 (http://127.0.0.1:9090/ui)"
echo ""
echo "配置管理："
echo "  clash update <订阅链接>    # 更新订阅配置"
echo "  clash mixin              # 查看 mixin 配置"
echo "  clash mixin -e           # 编辑 mixin 配置"
echo "  clash help               # 查看更多帮助"
echo ""

if [ "$CONFIG_SUCCESS" != "1" ]; then
    echo "[WARNING] 注意事项："
    echo "  由于配置下载失败，您需要："
    echo "  1. 手动编辑配置文件：$CLASH_CONFIG_RUNTIME"
    echo "  2. 或使用命令：clash update <订阅链接>"
    echo ""
fi

echo "配置文件位置："
echo "  主配置：$CLASH_CONFIG_RUNTIME"
echo "  Mixin：$CLASH_CONFIG_MIXIN"
echo ""

# 显示 Web UI 信息
_clash_ui

_okcat '[SUCCESS]' "fastclash 安装完成！开始使用吧！"
_quit