#!/bin/bash
# 和平精英辅助扩展脚本 - 纯净版
# 功能：卡密验证 + 辅助功能

MAX_ATTEMPTS=3
THEME_COLOR="32"
VERSION="12.0"
SDCARD="/sdcard"
[ ! -d "$SDCARD" ] && SDCARD="./"

# ==================== 卡密验证核心 ====================
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}"
}

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"
}

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
}

auth() {
    clear
    echo -e "\033[${THEME_COLOR}m===== 和平精英辅助 - 卡密验证 =====\033[0m"
    local attempts=0

    while [ $attempts -lt $MAX_ATTEMPTS ]; do
        read -s -p "请输入10位卡密：" input_card
        echo -e "\n"

        verify_card "$input_card"
        local result=$?

        case $result in
            0)
                echo -e "\033[32m✅ 卡密验证通过！正在启动辅助功能...\033[0m"
                return 0
                ;;
            10)
                echo -e "\033[31m❌ 卡密长度错误！必须为10位\033[0m"
                ;;
            20)
                echo -e "\033[31m❌ 卡密无效或被篡改！\033[0m"
                ;;
            30)
                echo -e "\033[31m❌ 卡密已过期！\033[0m"
                ;;
        esac

        attempts=$((attempts + 1))
        echo -e "\033[33m剩余验证次数：$((MAX_ATTEMPTS - attempts))\033[0m"
    done

    echo -e "\033[31m❌ 验证失败次数过多！脚本退出\033[0m"
    exit 1
}

# ==================== 辅助功能 ====================
start_cheat() {
    clear
    echo -e "\033[${THEME_COLOR}m===== 🚀 和平精英辅助功能启动 =====\033[0m"
    echo "当前时间：$(date +%Y-%m-%d_%H:%M:%S)"
    echo "脚本版本：v$VERSION"
    echo "4. 📱 鸿蒙系统适配（免Root运行）"
    echo "• 运行 管理员工具.sh 进行脚本更新"

    # 模拟功能运行（实际使用时替换为真实功能代码）
    while true; do
        sleep 1
        echo -e "\r\033[32m辅助功能运行中...（长按 HOME 键退出）\033[0m"
    done
}

# ==================== 启动流程 ====================
auth
start_cheat