#!/usr/bin/env python3
# Parse sgdisk --print output, output sfdisk MBR script (max 4 partitions)
# Skip "shadow copy" / unusual types. Keep Recovery + ESP + MSR + Windows NTFS.
import re, sys

# GPT type code → MBR id mapping
TYPE_MAP = {
    "2700": "27",  # Windows Recovery
    "EF00": "ef",  # EFI System
    "0C01": "c",   # Microsoft Reserved (MSR) - map to FAT32 LBA for MBR
    "0700": "7",   # Basic data (NTFS/HPFS/exFAT)
    "8300": "83",  # Linux filesystem
    "8200": "82",  # Linux swap
}
# Partitions to skip (type code)
SKIP_TYPES = {"FFFF"}  # Microsoft shadow copy

lines = sys.stdin.read().splitlines()
parts = []
in_table = False
for ln in lines:
    if ln.strip().startswith("Number"):
        in_table = True
        continue
    if not in_table:
        continue
    m = re.match(r"\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+\s+\S+)\s+(\S+)\s+(.*)", ln)
    if not m:
        continue
    num, start, end, size, code, name = m.group(1, 2, 3, 4, 5, 6)
    if code in SKIP_TYPES:
        continue
    parts.append((int(start), int(end), code, name.strip()))
# Sort by start sector
parts.sort()
# Limit to 4
parts = parts[:4]
# Detect Windows NTFS partition (largest 0700)
win_idx = None
for i, (s, e, code, name) in enumerate(parts):
    if code == "0700" and (win_idx is None or (parts[i][1]-parts[i][0]) > (parts[win_idx][1]-parts[win_idx][0])):
        win_idx = i
# Output sfdisk MBR script
print("label: dos")
print("unit: sectors")
for i, (s, e, code, name) in enumerate(parts, start=1):
    size = e - s + 1
    mbr_id = TYPE_MAP.get(code, "83")
    boot = " bootable" if (i-1) == win_idx else ""
    print(f"/dev/nbd0p{i} : start={s}, size={size}, type={mbr_id}{boot}")
