#!/bin/bash
# 卡密辅助脚本 - 纯净版（本地配置更新）
# 特性：免Root + 卡密生成 + 本地配置更新 + 防篡改

VERSION="12.0"
SDCARD="/sdcard"
[ ! -d "$SDCARD" ] && SDCARD="./"
CONFIG_FILE="${SDCARD}/update_config.txt"

# ==================== 本地更新功能 ====================
load_update_config() {
    if [ ! -f "$CONFIG_FILE" ]; then
        return 1
    fi
    source "$CONFIG_FILE"
    if [ -z "$MAIN_URL" ] || [ -z "$EXT_URL" ] || [ -z "$TARGET_PATH" ]; then
        return 1
    fi
    return 0
}

check_update() {
    clear
    echo -e "\033[36m===== 卡密辅助脚本1 v$VERSION =====\033[0m"
    echo -e "\033[33m===== 检查更新 =====\033[0m"

    # 加载配置
    if ! load_update_config; then
        echo -e "\033[31m❌ 未找到更新配置文件！\033[0m"
        echo -e "\033[33m请先运行 管理员工具.sh 配置更新链接\033[0m"
        sleep 3
        return
    fi

    # 检查网络连接
    if ! ping -c 1 -W 3 baidu.com > /dev/null 2>&1; then
        echo -e "\033[31m❌ 网络连接失败！\033[0m"
        sleep 2
        return
    fi

    # 提示更新
    echo -e "🔍 已加载更新配置！"
    echo -e "主脚本链接：$MAIN_URL"
    echo -e "扩展脚本链接：$EXT_URL"
    echo -e "目标路径：$TARGET_PATH"
    read -p "是否立即更新？（y/n，默认n）：" UPDATE_CHOICE

    if [[ "$UPDATE_CHOICE" =~ ^[Yy]$ ]]; then
        update_script
    else
        echo -e "\n\033[33m已取消更新\033[0m"
        sleep 1
    fi
}

update_script() {
    echo -e "\n\033[32m🚀 开始更新...\033[0m"

    # 备份旧脚本
    echo -e "📦 正在备份旧脚本..."
    if [ -f "${TARGET_PATH}/card_mgr.sh" ]; then
        cp "${TARGET_PATH}/card_mgr.sh" "${TARGET_PATH}/card_mgr.sh.bak.$(date +%Y%m%d%H%M%S)"
    fi
    if [ -f "${TARGET_PATH}/extension.sh" ]; then
        cp "${TARGET_PATH}/extension.sh" "${TARGET_PATH}/extension.sh.bak.$(date +%Y%m%d%H%M%S)"
    fi

    # 下载新主脚本
    echo -e "📥 正在下载主脚本..."
    MAIN_DOWNLOAD=$(curl -s -w "%{http_code}" -o "${TARGET_PATH}/card_mgr_new.sh" "$MAIN_URL")
    if [ "$MAIN_DOWNLOAD" != "200" ]; then
        echo -e "\033[31m❌ 主脚本下载失败！HTTP 状态码：$MAIN_DOWNLOAD\033[0m"
        rm -f "${TARGET_PATH}/card_mgr_new.sh"
        return
    fi

    # 下载新扩展脚本
    echo -e "📥 正在下载扩展脚本..."
    EXT_DOWNLOAD=$(curl -s -w "%{http_code}" -o "${TARGET_PATH}/extension_new.sh" "$EXT_URL")
    if [ "$EXT_DOWNLOAD" != "200" ]; then
        echo -e "\033[31m❌ 扩展脚本下载失败！HTTP 状态码：$EXT_DOWNLOAD\033[0m"
        rm -f "${TARGET_PATH}/card_mgr_new.sh" "${TARGET_PATH}/extension_new.sh"
        return
    fi

    # 覆盖旧脚本
    echo -e "🔧 正在更新脚本..."
    chmod +x "${TARGET_PATH}/card_mgr_new.sh" "${TARGET_PATH}/extension_new.sh"
    mv -f "${TARGET_PATH}/card_mgr_new.sh" "${TARGET_PATH}/card_mgr.sh"
    mv -f "${TARGET_PATH}/extension_new.sh" "${TARGET_PATH}/extension.sh"

    echo -e "\n\033[32m✅ 更新成功！\033[0m"
    echo -e "\033[33m提示：脚本将重启以应用新版本...\033[0m"
    sleep 3

    # 重启脚本
    exec bash "${TARGET_PATH}/card_mgr.sh"
}

# ==================== 卡密核心算法 ====================
generate_random() {
    local chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    local random=""
    for ((i=0; i<6; i++)); do
        random="${random}${chars:$((RANDOM % ${#chars})):1}"
    done
    echo "$random"
}

calculate_checksum() {
    local random="$1"
    local time_code="$2"
    local sum=0
    for ((i=0; i<${#random}; i++)); do
        sum=$((sum + $(printf "%d" "'${random:$i:1}")))
    done
    for ((i=0; i<${#time_code}; i++)); do
        sum=$((sum + $(printf "%d" "'${time_code:$i:1}")))
    done
    local checksum=$(printf "%02X" $((sum % 256)))
    echo "${checksum:0:2}"
}

generate_time_code() {
    local type="$1"
    local value="$2"
    if [ "$type" = "days" ]; then
        local days=$(printf "%02d" $value)
        echo "D${days: -1}"
    else
        local year_last=$(echo "$value" | cut -d'-' -f1 | cut -c 3-4)
        echo "Y${year_last: -1}"
    fi
}

parse_time_code() {
    local time_code="$1"
    local type="${time_code:0:1}"
    local value="${time_code:1:1}"
    local current_time=$(date +%s)

    if [ "$type" = "D" ]; then
        local days=$(( value == 0 ? 10 : value ))
        local expire_time=$((current_time + days * 86400))
    else
        local year=$((2020 + value))
        local expire_date="${year}-12-31"
        local expire_time=$(date -d "$expire_date" +%s)
    fi

    echo "$expire_time"
}

generate_card() {
    local type="$1"
    local value="$2"
    local random=$(generate_random)
    local time_code=$(generate_time_code "$type" "$value")
    local checksum=$(calculate_checksum "$random" "$time_code")
    local card="${random}${checksum}${time_code}"
    echo "$card"
}

verify_card() {
    local card="$1"
    if [ ${#card} -ne 10 ]; then
        return 10
    fi
    local random="${card:0:6}"
    local checksum="${card:6:2}"
    local time_code="${card:8:2}"
    local calculated_checksum=$(calculate_checksum "$random" "$time_code")
    if [ "$checksum" != "$calculated_checksum" ]; then
        return 20
    fi
    local expire_time=$(parse_time_code "$time_code")
    local current_time=$(date +%s)
    if [ "$current_time" -gt "$expire_time" ]; then
        return 30
    fi
    return 0
}

# ==================== 卡密生成功能 ====================
action_generate() {
    clear
    echo -e "\033[36m===== 卡密辅助脚本 v$VERSION =====\033[0m"
    echo -e "\033[32m===== 🎫 卡密生成（自定义有效期） =====\033[0m"
    local type_choice=""
    while true; do
        read -p "选择有效期方式（1=天数，2=日期，q=返回）：" type_choice
        if [[ "$type_choice" =~ ^[Qq]$|^[Qq][Uu][Ii][Tt]$ ]]; then
            echo "🔙 返回主菜单..."
            sleep 1
            return
        fi
        if [[ "$type_choice" =~ ^[12]$ ]]; then
            break
        fi
        echo -e "\033[31m❌ 无效选择！请输入 1、2 或 q\033[0m"
    done

    local type=""
    local value=""
    local expire_info=""

    if [ "$type_choice" = "1" ]; then
        while true; do
            read -p "输入有效天数（1-90，默认30，q=返回）：" days
            if [[ "$days" =~ ^[Qq]$|^[Qq][Uu][Ii][Tt]$ ]]; then
                echo "🔙 返回主菜单..."
                sleep 1
                return
            fi
            [ -z "$days" ] && days=30
            if [[ "$days" =~ ^[0-9]+$ ]] && [ "$days" -ge 1 ] && [ "$days" -le 90 ]; then
                type="days"
                value="$days"
                expire_info="${days}天"
                break
            fi
            echo -e "\033[31m❌ 无效天数！请输入 1-90 之间的数字，或 q 返回\033[0m"
        done
    else
        while true; do
            read -p "输入具体日期（如 2026，默认2026-12-31，q=返回）：" date_input
            if [[ "$date_input" =~ ^[Qq]$|^[Qq][Uu][Ii][Tt]$ ]]; then
                echo "🔙 返回主菜单..."
                sleep 1
                return
            fi
            [ -z "$date_input" ] && date_input="2026-12-31"
            if [[ "$date_input" =~ ^[0-9]{4}$ ]]; then
                date_input="${date_input}-12-31"
            fi
            if [[ "$date_input" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
                type="date"
                value="$date_input"
                expire_info="$date_input"
                break
            fi
            echo -e "\033[31m❌ 无效日期！请输入 2026 或 2026-12-31，或 q 返回\033[0m"
        done
    fi

    local card=$(generate_card "$type" "$value")
    echo -e "\n🔍 生成卡密并验证..."
    if verify_card "$card"; then
        local txt_file="$SDCARD/card_${card}.txt"
        cat > "$txt_file" << EOF
【卡密辅助卡密】
卡密：$card
有效期：$expire_info
生成时间：$(date +%Y-%m-%d_%H:%M:%S)
版本：$VERSION
状态：有效

【使用说明】
1. 复制卡密运行 extension.sh
2. 免Root运行，适配鸿蒙系统
3. 运行 管理员工具.sh 配置更新
EOF

        echo -e "\033[32m🎉 卡密生成成功！\033[0m"
        echo "🔑 卡密：$card（复制此卡密！）"
        echo "📅 有效期：$expire_info"
        echo "✅ 状态：100%有效"
        echo -e "\n📄 卡密已保存至：$txt_file"
    else
        echo -e "\033[31m❌ 卡密生成失败！请重新生成\033[0m"
    fi

    read -p "按任意键返回主菜单..." -n 1
}

# ==================== 卡密验证功能 ====================
action_verify() {
    clear
    echo -e "\033[36m===== 卡密辅助脚本 v$VERSION =====\033[0m"
    echo -e "\033[32m===== ✅ 卡密验证 =====\033[0m"
    local card=""
    while true; do
        read -p "输入卡密（10位，q=返回）：" card
        if [[ "$card" =~ ^[Qq]$|^[Qq][Uu][Ii][Tt]$ ]]; then
            echo "🔙 返回主菜单..."
            sleep 1
            return
        fi
        if [ ${#card} -eq 10 ]; then
            break
        fi
        echo -e "\033[31m❌ 卡密长度错误！必须为10位\033[0m"
    done

    verify_card "$card"
    local result=$?

    case $result in
        0)
            local time_code="${card:8:2}"
            local expire_time=$(parse_time_code "$time_code")
            local expire_date=$(date -d "@$expire_time" +%Y-%m-%d)
            echo -e "\n\033[32m✅ 卡密验证通过！\033[0m"
            echo "📅 有效期至：$expire_date"
            echo -e "\033[33m提示：运行 extension.sh 启动辅助功能\033[0m"
            ;;
        10)
            echo -e "\n\033[31m❌ 卡密长度错误！必须为10位\033[0m"
            ;;
        20)
            echo -e "\n\033[31m❌ 卡密无效或被篡改！\033[0m"
            ;;
        30)
            echo -e "\n\033[31m❌ 卡密已过期！请联系管理员获取新卡密\033[0m"
            ;;
    esac

    read -p "按任意键返回主菜单..." -n 1
}

# ==================== 主菜单 ====================
main_menu() {
    while true; do
        clear
        echo -e "\033[36m===== 卡密辅助脚本 v$VERSION =====\033[0m"
        echo -e "\033[33m===== 主菜单 =====\033[0m"
        echo "1. 🎫 生成卡密（自定义有效期）"
        echo "2. ✅ 验证卡密"
        echo "3. 🔄 检查更新"
        echo "4. 🚪 退出脚本"
        read -p "请选择操作（1-4）：" choice

        case $choice in
            1) action_generate ;;
            2) action_verify ;;
            3) check_update ;;
            4)
                echo -e "\n\033[32m👋 感谢使用！脚本已退出\033[0m"
                exit 0
                ;;
            *)
                echo -e "\033[31m❌ 无效选择！请输入 1-4\033[0m"
                sleep 1
                ;;
        esac
    done
}

# ==================== 启动流程 ====================
main_menu