#!/usr/bin/env bash
# 解锁 Bootloader 之后使用：将 Magisk 修补后的镜像刷入 boot 或 init_boot
# 用法：
#   FASTBOOT_FLASH_CONFIRM=yes ./xiaomi_fastboot_flash_magisk.sh /path/to/magisk_patched.img boot
#   FASTBOOT_FLASH_CONFIRM=yes ./xiaomi_fastboot_flash_magisk.sh /path/to/magisk_patched.img init_boot
set -euo pipefail

IMG="${1:-}"
PART="${2:-boot}"

usage() {
  echo "用法: FASTBOOT_FLASH_CONFIRM=yes $0 <magisk修补镜像路径> [boot|init_boot]"
  echo "  默认分区: boot"
  echo "  刷入前请确认: BL 已解锁、镜像来自与本机 MIUI 版本一致的 boot/init_boot 修补结果。"
  exit 1
}

[[ -z "$IMG" || ! -f "$IMG" ]] && usage
[[ "$PART" != "boot" && "$PART" != "init_boot" ]] && usage

if [[ "${FASTBOOT_FLASH_CONFIRM:-}" != "yes" ]]; then
  echo "拒绝执行：为防止误刷，请设置环境变量 FASTBOOT_FLASH_CONFIRM=yes"
  echo "示例: FASTBOOT_FLASH_CONFIRM=yes $0 \"$IMG\" $PART"
  exit 2
fi

if ! command -v fastboot >/dev/null 2>&1; then
  echo "未找到 fastboot，请安装 Android platform-tools"
  exit 3
fi

FB_OUT=$(fastboot devices 2>/dev/null | awk 'NF>=2 && $2=="fastboot"{print $1}' | head -1)
if [[ -z "$FB_OUT" ]]; then
  echo "未检测到 fastboot 设备。请先: adb reboot bootloader"
  exit 4
fi

echo ">>> 设备: $FB_OUT"
echo ">>> 将执行: fastboot flash $PART $IMG"
fastboot flash "$PART" "$IMG"
fastboot reboot
echo ">>> 已重启，开机后执行: adb shell su -c id"
