#!/bin/bash
# v2: Use sfdisk explicit MBR layout from sgdisk parse (handles 5+ GPT partitions correctly)
set -e
QCOW2="${1:?qcow2 path required}"
NBD=/dev/nbd0
LOG=/tmp/fix-boot-$(basename "$QCOW2" .qcow2).log
exec > >(tee -a "$LOG") 2>&1
echo "=== $(date) fix-boot-windows v2 $QCOW2 ==="

which ms-sys >/dev/null || { echo "ABORT: ms-sys missing"; exit 1; }
which sgdisk sfdisk ntfsfix qemu-nbd parted blkid >/dev/null || { echo "ABORT: tools missing"; exit 1; }

modprobe nbd max_part=16 2>/dev/null || true
qemu-nbd --disconnect $NBD 2>/dev/null || true
sleep 1
qemu-nbd --connect=$NBD "$QCOW2"
sleep 2

echo "--- GPT layout before ---"
sgdisk --print $NBD | tee /tmp/sgdisk-print.txt

echo "--- Parse GPT and build sfdisk MBR script ---"
python3 /NFS01/migrate/gpt_to_mbr_layout.py < /tmp/sgdisk-print.txt > /tmp/mbr-layout.sfdisk
cat /tmp/mbr-layout.sfdisk

echo "--- Wipe old GPT (so we can use sfdisk) ---"
sgdisk --zap-all $NBD || true
sleep 1
partprobe $NBD; sleep 2

echo "--- Apply MBR via sfdisk ---"
sfdisk $NBD < /tmp/mbr-layout.sfdisk
sleep 2
partprobe $NBD; sleep 2

echo "--- MBR layout after ---"
fdisk -l $NBD

echo "--- Write Win7+ MBR bootcode ---"
ms-sys --mbr7 -f $NBD

sleep 3; partprobe $NBD; sleep 2
echo "--- Find Windows NTFS partition (largest) ---"
WIN_PART=$(for P in ${NBD}p*; do
  T=$(blkid -o value -s TYPE "$P" 2>/dev/null)
  S=$(blockdev --getsize64 "$P" 2>/dev/null)
  [ "$T" = ntfs ] && echo "$S $P"
done | sort -nr | head -1 | awk "{print \$2}")
echo "WIN_PART=$WIN_PART"
[ -z "$WIN_PART" ] && { echo "ABORT: no NTFS partition found"; qemu-nbd --disconnect $NBD; exit 2; }

echo "--- Write NTFS PBR Win7+ + ntfsfix ---"
ms-sys --ntfs -f "$WIN_PART"
ntfsfix -d "$WIN_PART" || true

echo "--- Mount + copy bootmgr ---"
mkdir -p /mnt/win-fix
mount -t ntfs-3g -o force "$WIN_PART" /mnt/win-fix
if [ -f /mnt/win-fix/Windows/Boot/PCAT/bootmgr ]; then
  cp /mnt/win-fix/Windows/Boot/PCAT/bootmgr /mnt/win-fix/bootmgr
  echo "bootmgr copied"
else
  echo "WARN: bootmgr not at expected path"
fi
umount /mnt/win-fix
qemu-nbd --disconnect $NBD
echo "=== $(date) fix-boot-windows v2 DONE ==="
