import os
import shutil
import subprocess
from pathlib import Path

# =========================
# Configuration
# =========================
ISO_NAME = "hdgl-monolith-debian.iso"
ISO_TREE = Path("./hdgl_mono_iso")
BOOT_DIR = ISO_TREE / "boot"
GRUB_DIR = ISO_TREE / "boot/grub"

PY_MONOLITH = Path("./monolith.py")
HDGL_ELF = Path("./hdgl_monolith.elf")
DEBIAN_ROOTFS = Path("./debian_rootfs")

# =========================
# Step 1: Fetch minimal Debian rootfs
# =========================
def fetch_debian_rootfs():
    print("[+] Bootstrapping minimal Debian rootfs...")
    if DEBIAN_ROOTFS.exists():
        shutil.rmtree(DEBIAN_ROOTFS)
    DEBIAN_ROOTFS.mkdir()
    subprocess.run([
        "debootstrap", "--arch=amd64", "stable", str(DEBIAN_ROOTFS),
        "http://deb.debian.org/debian"
    ], check=True)
    print("[+] Debian rootfs ready.")

# =========================
# Step 2: Compile HDGL monolith
# =========================
def compile_monolith():
    print("[+] Compiling HDGL monolith (GPU-native)...")
    if HDGL_ELF.exists():
        HDGL_ELF.unlink()
    subprocess.run([
        "pyinstaller", "--onefile", "--name", "hdgl_monolith", str(PY_MONOLITH)
    ], check=True)
    built_path = Path("./dist/hdgl_monolith")
    if os.name == "nt":
        built_path = built_path.with_suffix(".exe")
    shutil.copy2(built_path, HDGL_ELF)
    print("[+] Monolith compiled:", HDGL_ELF)

# =========================
# Step 3: Prepare ISO tree
# =========================
def prepare_iso_tree():
    print("[+] Preparing ISO folder tree...")
    if ISO_TREE.exists():
        shutil.rmtree(ISO_TREE)
    BOOT_DIR.mkdir(parents=True, exist_ok=True)
    GRUB_DIR.mkdir(parents=True, exist_ok=True)

    # Copy HDGL monolith and Debian rootfs into ISO
    shutil.copy2(HDGL_ELF, BOOT_DIR / "hdgl_monolith.elf")
    shutil.copytree(DEBIAN_ROOTFS, ISO_TREE / "debian_rootfs")

    # GRUB config: boot HDGL monolith
    grub_cfg = GRUB_DIR / "grub.cfg"
    grub_cfg.write_text(f"""
set default=0
set timeout=5

menuentry "HDGL Monolith Debian" {{
    linux /boot/hdgl_monolith.elf
    # HDGL itself will mount debian_rootfs and boot it internally
}}
""")
    print("[+] ISO tree ready.")

# =========================
# Step 4: Build ISO
# =========================
def build_iso():
    print(f"[+] Building ISO: {ISO_NAME}")
    subprocess.run([
        "xorriso", "-as", "mkisofs",
        "-o", ISO_NAME,
        "-b", "boot/grub/i386-pc/eltorito.img",
        "-c", "boot.cat",
        "-no-emul-boot",
        "-boot-load-size", "4",
        "-boot-info-table",
        str(ISO_TREE)
    ], check=True)
    print(f"[+] ISO {ISO_NAME} created successfully.")

# =========================
# Main
# =========================
if __name__ == "__main__":
    fetch_debian_rootfs()
    compile_monolith()
    prepare_iso_tree()
    build_iso()
    print("[+] HDGL Monolithic ISO ready — boots HDGL with Debian inside!")
