#!/bin/bash
# ==============================================================================
# Auto-Discovery Pre-Reboot NAND Refresh Script
#
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 https://mememodoki.jp
#
# Developed via Human-AI Collaboration
# (Concept & Verification: Human / Code & Refactoring: AI)
# ==============================================================================

# 1) Read README and LICENSE files.
# 2) mount /boot (if unmounted under normal operation), or this script skips silently.
# 3) Run as root, or simply fails GPT/MBR header reading.

set -e

echo "[INFO] Starting auto-discovery scan for boot-critical storage devices..."

# 1. マウントポイント（/boot および /）から直接デバイスパスを抽出
BOOT_TARGET=$(lsblk -p -s -n -o NAME,MOUNTPOINT 2>/dev/null | grep -e " /boot$" | awk '{print $1}')
ROOT_TARGET=$(lsblk -p -s -n -o NAME,MOUNTPOINT 2>/dev/null | grep -e " /$" | awk '{print $1}')

BOOT_DEVS=""
ROOT_DEVS=""

# 2. 抽出したデバイスパスから上位/下位の依存デバイス構造（LUKS, 物理ディスク）を取得
if [ -n "$BOOT_TARGET" ]; then
    BOOT_DEVS=$(lsblk -p -s -n -o NAME "$BOOT_TARGET" 2>/dev/null)
fi

if [ -n "$ROOT_TARGET" ]; then
    ROOT_DEVS=$(lsblk -p -s -n -o NAME "$ROOT_TARGET" 2>/dev/null)
fi

# 重複を排除してターゲット一覧を生成
ALL_TARGETS=$(echo -e "${BOOT_DEVS}\n${ROOT_DEVS}" | grep -v '^$' | sort -u)

if [ -z "$ALL_TARGETS" ]; then
    echo "[WARN] No boot-dependent storage devices detected. Skipping scan."
    exit 0
fi

echo "[INFO] Detected boot dependencies:"
echo "$ALL_TARGETS"
echo "------------------------------------------------------------------"

# 3. 検出された各ターゲットに対して適切なピンポイントリードを実行
for DEV in $ALL_TARGETS; do
    if [ ! -b "$DEV" ]; then
        continue
    fi

    DEV_TYPE=$(lsblk -n -o TYPE "$DEV" 2>/dev/null | head -n1)
    FS_TYPE=$(lsblk -n -o FSTYPE "$DEV" 2>/dev/null | head -n1)

    echo "[INFO] Scanning: $DEV (Type: $DEV_TYPE, FSTYPE: $FS_TYPE)"

    if [ "$FS_TYPE" = "crypto_LUKS" ]; then
        # LUKSパーティション: ヘッダー領域（先頭16MB）をダイレクトリード
        echo "  -> Reading LUKS header region (First 16MB)..."
        if ! dd if="$DEV" of=/dev/null bs=1M count=16 iflag=direct status=none; then
            echo "[CRITICAL] Read error detected on LUKS header: $DEV"
            exit 1
        fi

    elif [ "$DEV_TYPE" = "disk" ]; then
        # 物理ディスク全体: GPT/MBRパーティションテーブル（先頭2MB）をダイレクトリード
        echo "  -> Reading partition table region (First 2MB)..."
        if ! dd if="$DEV" of=/dev/null bs=1M count=2 iflag=direct status=none; then
            echo "[CRITICAL] Read error detected on partition table: $DEV"
            exit 1
        fi

    elif [ "$DEV_TYPE" = "part" ] && [[ "$FS_TYPE" =~ ^(vfat|ext4|xfs)$ ]]; then
        # ブートパーティション全域をダイレクトリード
        echo "  -> Reading boot partition entirely..."
        if ! dd if="$DEV" of=/dev/null bs=4M iflag=direct status=none; then
            echo "[CRITICAL] Read error detected on boot partition: $DEV"
            exit 1
        fi
    fi
done

echo "------------------------------------------------------------------"
echo "[INFO] Completed successfully. NAND ECC refresh triggered for essential regions."
