#!/system/bin/sh
# 而不是简单的 #!/bin/sh
# 颜色定义
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
CYAN='\033[1;36m'
NC='\033[0m'

# 目标文件路径
TARGET_FILES="/data/data/com.tencent.tmgp.dfm/files/ano_tmp/mrpcs_a_cd.data /data/data/com.tencent.tmgp.dfm/files/ano_tmp/custom_cache/mrpcs_a_cd.data"

# 腾讯微云配置
WEIYUN_API="https://share.weiyun.com/s6fsKskj"
CURRENT_VERSION="v7.2"

# 获取网络内容
GetWebContent() {
    local url="$1"
    if which wget >/dev/null 2>&1; then
        wget --no-check-certificate -qO- "$url" 2>/dev/null
    else
        curl -s -k "$url"
    fi
}

# 检查并执行更新
CheckAndApplyUpdate() {
    echo -e "${YELLOW}\n正在检查更新...${NC}"
    
    # 从腾讯微云获取更新信息
    local noteContent=$(GetWebContent "$WEIYUN_API")
    if [ -z "$noteContent" ]; then
        echo -e "${RED}无法从腾讯微云获取更新信息${NC}"
        return 1
    fi
    
    # 提取最新版本号
    local latestVersion=$(echo "$noteContent" | grep -Eo "最新版本[:：][ ]*(v?[0-9]+.[0-9]+)" | head -1 | sed -E 's/最新版本[:：][ ]*//')
    if [ -z "$latestVersion" ]; then
        echo -e "${RED}未找到版本信息${NC}"
        return 1
    fi
    
    # 版本比较
    if [ "$latestVersion" = "$CURRENT_VERSION" ]; then
        echo -e "${GREEN}当前已是最新版本 ($CURRENT_VERSION)${NC}"
        return 1
    fi
    
    echo -e "${YELLOW}发现新版本: $latestVersion (当前版本: $CURRENT_VERSION)${NC}"
    
    # 提取下载链接
    local downloadUrl=$(echo "$noteContent" | grep -Eo "https?://[^[:space:]]+\.(apk|bin|sh|data|zip)" | head -1)
    if [ -z "$downloadUrl" ]; then
        echo -e "${RED}未找到有效下载链接${NC}"
        return 1
    fi
    
    echo -e "${CYAN}下载链接: $downloadUrl${NC}"
    
    # 使用可写目录下载
    local tempDir="/data/local/tmp/dfm_update"
    mkdir -p "$tempDir"
    local tempFile="$tempDir/update_$(date +%s).sh"
    
    echo -e "${YELLOW}正在下载更新...${NC}"
    
    if which wget >/dev/null 2>&1; then
        wget --no-check-certificate -O "$tempFile" "$downloadUrl"
    else
        curl -k -o "$tempFile" "$downloadUrl"
    fi
    
    if [ $? -ne 0 ] || [ ! -s "$tempFile" ]; then
        echo -e "${RED}下载失败${NC}"
        rm -rf "$tempDir"
        return 1
    fi
    
    # 设置可执行权限
    chmod 755 "$tempFile"
    
    # 执行更新脚本
    echo -e "${GREEN}下载完成，准备安装...${NC}"
    if ! "$tempFile"; then
        echo -e "${RED}更新脚本执行失败${NC}"
        rm -rf "$tempDir"
        return 1
    fi
    
    echo -e "${GREEN}\n更新成功完成!${NC}"
    echo -e "${YELLOW}更新内容:${NC}"
    echo "$noteContent" | grep -A 10 "更新内容[:：]"
    
    rm -rf "$tempDir"
    return 0
}

# 伪开启预防设备脸
FakePrevention() {
    echo -e "${YELLOW}\n正在开启预防设备脸功能...${NC}"
    
    # 生成随机设备ID
    local name=""
    for i in 1 2 3 4 5 6 7 8; do
        name=$name$(($RANDOM % 9 + 1))
    done
    
    # 修改设备序列号
    if which resetprop >/dev/null 2>&1; then
        resetprop ro.serialno "$name"
    fi
    echo -e "${GREEN}设备序列号已修改为: $name${NC}"
    
    # 清理残留文件
    rm -rf /data/user/0/com.tencent.tmgp.pubgmhd/files/ano_tmp
    rm -rf /data/data/com.tencent.tmgp.pubgmhd/files/ano_tmp
    
    echo -e "${YELLOW}预防设备脸功能已开启!${NC}"
    sleep 2
}

# 检查文件权限
CheckPermission() {
    local file="$1"
    if [ -e "$file" ]; then
        local perm=$(stat -c "%a" "$file" 2>/dev/null)
        if [ "$perm" = "0" ]; then
            return 0
        fi
    fi
    return 1
}

# 修复文件权限
FixPermission() {
    local file="$1"
    local filename=$(basename "$file")
    
    if chmod 000 "$file" 2>/dev/null; then
        echo -e "${GREEN}✅ $filename 修复成功 (chmod方式)${NC}"
        return 0
    fi
    
    if which busybox >/dev/null 2>&1; then
        if busybox chmod 000 "$file" 2>/dev/null; then
            echo -e "${GREEN}✅ $filename 修复成功 (BusyBox方式)${NC}"
            return 0
        fi
    fi
    
    if : > "$file" 2>/dev/null; then
        echo -e "${GREEN}✅ $filename 修复成功 (清空文件)${NC}"
        return 0
    fi
    
    echo -e "${RED}❌ $filename 所有修复方式均失败${NC}"
    return 1
}

# 权限监控
MonitorPermissions() {
    local checkInterval=5
    local checkCount=0
    
    echo -e "${YELLOW}\n正在准备系统环境...${NC}"
    
    local selinux=$(getenforce 2>/dev/null)
    if [ "$selinux" = "Enforcing" ]; then
        echo -e "${YELLOW}临时禁用SELinux强制模式...${NC}"
        setenforce 0
    fi
    
    echo -e "${GREEN}系统准备就绪，开始监控...${NC}"
    
    while true; do
        checkCount=$((checkCount + 1))
        echo -e "${PURPLE}\n🔍 检查轮次: $checkCount [$(date +%T)]${NC}"
        
        for file in $TARGET_FILES; do
            local filename=$(basename "$file")
            
            if [ -e "$file" ]; then
                if CheckPermission "$file"; then
                    echo -e "${GREEN}✓ $filename 状态正常${NC}"
                else
                    echo -e "${RED}⚠ 检测到异常权限: $filename${NC}"
                    FixPermission "$file"
                fi
            else
                echo -e "${BLUE}⏳ 等待文件: $filename...${NC}"
            fi
        done
        
        local i=$checkInterval
        while [ $i -gt 0 ]; do
            echo -ne "${CYAN}⏳ 下次检查: ${YELLOW}$i秒后 ${RED}(Ctrl+C退出)${NC}\r"
            sleep 1
            i=$((i - 1))
        done
        echo
    done
}

# 显示主菜单
ShowMenu() {
    clear
    echo -e "${PURPLE}╔════════════════════════════════════╗"
    echo -e "║${GREEN}🛡️ JY工具箱 $CURRENT_VERSION ${PURPLE}║"
    echo -e "╚════════════════════════════════════╝${NC}"
    echo -e "${CYAN}1. 开启预防设备脸"
    echo -e "${CYAN}2. 开启修改权限监控"
    echo -e "${CYAN}3. 检查更新"
    echo -e "${RED}4. 退出程序${NC}"
    echo -e "${PURPLE}══════════════════════════════════════${NC}"
    echo -n "请选择操作 (1-4): "
}

# 主程序
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}✖ 需要root权限执行！${NC}"
    exit 1
fi

# 主菜单
while true; do
    ShowMenu
    
    read -r choice
    
    case "$choice" in
        1)
            FakePrevention
            ;;
        2)
            MonitorPermissions
            ;;
        3)
            if CheckAndApplyUpdate; then
                exit 0
            fi
            ;;
        4)
            echo -e "${GREEN}退出程序...${NC}"
            exit 0
            ;;
        *)
            echo -e "${RED}无效选择，请重新输入!${NC}"
            sleep 1
            ;;
    esac
    
    echo -ne "\n按Enter键继续..."
    read -r
done

exit 0