
#!/bin/bash
# EMMC启动修复工具 v2.0
# 功能：自动检测并修复EMMC启动配置问题

set -euo pipefail

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 日志函数
log() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}"
}

# 错误处理
error_exit() {
    echo -e "${RED}[ERROR] $1${NC}" >&2
    exit 1
}

# 检测root权限
check_root() {
    [ "$(id -u)" = "0" ] || error_exit "此脚本需要root权限运行"
}

# 主修复函数
main_repair() {
    check_root
    
    log "开始系统检测..."
    EMMC_DEVICE="/dev/mmcblk2"
    [ -b "$EMMC_DEVICE" ] || error_exit "未检测到EMMC设备"

    ROOT_PARTITION="${EMMC_DEVICE}p4"
    [ -b "$ROOT_PARTITION" ] || error_exit "未找到根分区"

    UUID=$(blkid -s UUID -o value "$ROOT_PARTITION" 2>/dev/null || true)
    ROOT_SPEC=${UUID:-$ROOT_PARTITION}

    log "修改系统配置..."
    # 更新uEnv.txt
    [ -f "/boot/uEnv.txt" ] && \
        sed -i "s|root=.*|root=$ROOT_SPEC|g" "/boot/uEnv.txt"

    # 更新extlinux配置
    [ -d "/boot/extlinux" ] && \
        find "/boot/extlinux" -name "*.conf" -exec sed -i "s|root=.*|root=$ROOT_SPEC|g" {} +

    # 更新fstab
    [ -f "/etc/fstab" ] && \
        sed -i "s|^[^#].* / |$ROOT_SPEC / |" "/etc/fstab"

    sync
    log "${GREEN}修复完成！请重启设备${NC}"
}

main_repair
