#!/system/bin/sh
set -e

# 初始化环境
export PATH="/system/bin:$PATH"
LOGFILE="/dev/null"  # 可替换为实际日志路径

# 预定义颜色代码（兼容不支持终端的场景）
COLOR_NORMAL=""
COLOR_GREEN=""
COLOR_RED=""
COLOR_YELLOW=""
[ -t 1 ] && {
    COLOR_NORMAL="\033[0m"
    COLOR_GREEN="\033[32m"
    COLOR_RED="\033[31m"
    COLOR_YELLOW="\033[33m"
}

# 函数：带时间戳的日志输出
log() {
    echo "${COLOR_YELLOW}[$(date '+%T')] $1${COLOR_NORMAL}"
}

# 函数：致命错误处理
abort() {
    echo "${COLOR_RED}ERROR: $1${COLOR_NORMAL}" >&2
    exit 1
}

# 权限检查
[ "$(id -u)" -ne 0 ] && abort "请以root权限运行此脚本"

# 临时文件清理
trap 'rm -f dtb.* dts.dtb.* dtbo_new.img 2>/dev/null' EXIT

###########################
### 第一阶段：解包与重打包 ###
###########################
log "开始处理dtbo镜像..."
log "步骤1/4 解包dtbo.img"
./bin/mkdtimg dump dtbo.img -b dtb >$LOGFILE 2>&1 || abort "dtbo解包失败"

log "步骤2/4 转换dtb至dts"
for dtb_file in dtb.*; do
    [ -f "$dtb_file" ] || continue
    log "正在处理: $dtb_file"
    ./bin/dtc -I dtb -O dts -@ -o "${dtb_file}.dts" "$dtb_file" >$LOGFILE 2>&1 || abort "DTB转DTS失败"
    mv "${dtb_file}.dts" "dts.${dtb_file}"
done

log "步骤3/4 修改品牌标识符"
sed_modified=false
for dts_file in dts.dtb.*; do
    [ -f "$dts_file" ] || continue
    sed -i 's/HMBIRD_OGKI/HMBIRD_GKI/g' "$dts_file"
    grep -q 'HMBIRD_GKI' "$dts_file" && sed_modified=true
done
$sed_modified || abort "关键字符串替换未生效"

log "步骤4/4 重新打包dtbo"
for dts_file in dts.dtb.*; do
    [ -f "$dts_file" ] || continue
    ./bin/dtc -I dts -O dtb -@ -o "${dts_file}.dtb" "$dts_file" >$LOGFILE 2>&1 || abort "DTS转DTB失败"
    mv "${dts_file}.dtb" "${dts_file#dts.}"
done

./bin/mkdtimg create dtbo_new.img dtb.* >$LOGFILE 2>&1 || abort "dtbo重组失败"
log "第一阶段完成，生成文件大小: $(du -sh dtbo_new.img | cut -f1)"

###########################
### 第二阶段：分区刷写验证 ###
###########################
SOURCE="dtbo_new.img"
TARGET="dtbo.img"

get_slot_info() {
    current_slot=$(getprop ro.boot.slot_suffix 2>/dev/null)
    [ -z "$current_slot" ] && abort "未检测到A/B分区，请确认设备支持A/B系统"
    target_slot=$([ "$current_slot" = "_a" ] && echo "_b" || echo "_a")
    log "分区槽信息：当前槽位=${current_slot} 目标槽位=${target_slot}"
}

verify_partition() {
    dtbo_block=$(find /dev/block -type l -name "dtbo$1" 2>/dev/null | head -n1)
    [ -b "$dtbo_block" ] || abort "无法定位dtbo分区: dtbo$1"
    log "验证分区可写性：[ $dtbo_block ]"
    dd if=/dev/zero of="$dtbo_block" bs=1 count=1 conv=notrunc 2>/dev/null || {
        echo "${COLOR_YELLOW}警告：分区可能处于只读状态，尝试重新挂载..."
        blockdev --setrw "$dtbo_block" 2>/dev/null || abort "分区写保护解除失败"
    }
}

get_slot_info
verify_partition "$target_slot"

log "开始刷写分区..."
dd if="$SOURCE" of="$dtbo_block" bs=1M 2>/dev/null || abort "分区刷写失败"
sync
log "刷写完成，等待缓存同步"

log "执行分区校验..."
dd if="$dtbo_block" of="$TARGET" bs=1M 2>/dev/null || abort "验证数据提取失败"

log "操作成功完成！最终文件信息："
ls -l "$TARGET" | awk '{printf "  大小: %sB  修改时间: %s %s\n", $5, $6, $7}'
