#!/usr/bin/env python3
"""Create the cidata autoinstall drive matching Omarchy 4.5.0 (ISO 7.2.15)."""
import json
import os
import subprocess

HERE = os.path.dirname(os.path.abspath(__file__))
MIB = 1024 * 1024
GIB = 1024 * MIB
DISK_GIB = 40
ROOT_UUID = "8c2c2b92-1070-455d-b76a-56263bab24aa"
BOOT_UUID = "ea21d3f2-82bb-49cc-ab5d-6f81ae94e18d"


def sh(cmd):
    subprocess.run(cmd, shell=True, check=True)


def size(n):
    return {"sector_size": {"unit": "B", "value": 512}, "unit": "B", "value": n}


def main():
    disk_mib = DISK_GIB * 1024
    boot_start = MIB
    boot_size = 2 * GIB
    root_start = boot_start + boot_size
    root_size = (disk_mib - (root_start // MIB) - 1) * MIB

    password = "omarchy"
    sh("test -f ~/.ssh/id_ed25519 || ssh-keygen -q -t ed25519 -N '' -f ~/.ssh/id_ed25519")
    pubkey = open(os.path.expanduser("~/.ssh/id_ed25519.pub")).read().strip()
    phash = subprocess.run(["openssl", "passwd", "-6", password], capture_output=True,
                           text=True, check=True).stdout.strip()

    config = {
        "app_config": None,
        "archinstall-language": "English",
        "auth_config": {},
        "audio_config": {"audio": "pipewire"},
        "bootloader_config": {"bootloader": "Limine", "uki": False, "removable": False},
        "custom_commands": [],
        "omarchy_install": {
            "input_method": "none",
            "input_xkb_layout": "",
            "language": "en",
            "mode": "full_disk",
            "defer_provisioning": False,
            "target_mount": "/mnt",
            "boot": {
                "esp_mount": "/boot",
                "esp_path": "/EFI/limine",
                "efi_binary": "limine_x64.efi",
                "enable_fallback": True,
            },
            "storage": {"kernel": "linux-omarchy"},
        },
        "disk_config": {
            "config_type": "default_layout",
            "device_modifications": [{
                "device": "/dev/vda",
                "wipe": True,
                "partitions": [
                    {
                        "btrfs": [], "dev_path": None,
                        "flags": ["boot", "esp"], "fs_type": "fat32",
                        "mount_options": [], "mountpoint": "/boot",
                        "obj_id": BOOT_UUID, "size": size(boot_size),
                        "start": size(boot_start), "status": "create", "type": "primary",
                    },
                    {
                        "btrfs": [
                            {"mountpoint": "/", "name": "@"},
                            {"mountpoint": "/home", "name": "@home"},
                            {"mountpoint": "/var/log", "name": "@log"},
                            {"mountpoint": "/var/cache/pacman/pkg", "name": "@pkg"},
                        ],
                        "dev_path": None, "flags": [], "fs_type": "btrfs",
                        "mount_options": ["compress=zstd"], "mountpoint": None,
                        "obj_id": ROOT_UUID, "size": size(root_size),
                        "start": size(root_start), "status": "create", "type": "primary",
                    },
                ],
            }],
            # Measurement VM: skip LUKS so TCG does not spend minutes in
            # Argon2id at every boot. Encryption has no bearing on idle RAM.
            "disk_encryption": {
                "encryption_type": "no_encryption",
                "lvm_volumes": [],
                "partitions": [],
            },
        },
        "hostname": "omarchyvm",
        "kernels": ["linux-omarchy"],
        "network_config": {"type": "iso"},
        "ntp": True,
        "parallel_downloads": 8,
        "script": None,
        "services": [],
        "swap": True,
        "timezone": "UTC",
        "locale_config": {"kb_layout": "us", "sys_enc": "UTF-8", "sys_lang": "en_US.UTF-8"},
        "mirror_config": {
            "custom_repositories": [], "custom_servers": [],
            "mirror_regions": {}, "optional_repositories": [],
        },
        "packages": ["base-devel", "git", "omarchy-keyring", "omarchy-settings", "omarchy"],
        "profile_config": {"gfx_driver": None, "greeter": None, "profile": {}},
        "version": "3.0.9",
    }
    creds = {
        "root_enc_password": phash,
        "users": [{"enc_password": phash, "groups": [], "sudo": True, "username": "omarchy"}],
    }

    stage = os.path.join(HERE, "cidata-stage")
    sh(f"rm -rf {stage} && mkdir -p {stage}")
    for name, data in (("user_configuration.json", config), ("user_credentials.json", creds)):
        with open(os.path.join(stage, name), "w") as f:
            json.dump(data, f, indent=4)
    with open(os.path.join(stage, "authorized_keys"), "w") as f:
        f.write(pubkey + "\n")

    cidata = os.path.join(HERE, "cidata.img")
    sh(f"truncate -s 16M {cidata}")
    sh(f"mkfs.vfat -n cidata {cidata} >/dev/null")
    mnt = "/mnt/resreq-cidata"
    sh(f"sudo mkdir -p {mnt} && sudo mount -o loop {cidata} {mnt}")
    try:
        for name in ("user_configuration.json", "user_credentials.json", "authorized_keys"):
            sh(f"sudo cp {stage}/{name} {mnt}/{name}")
    finally:
        sh(f"sudo umount {mnt}")
    print(json.dumps({
        "boot": {"start": boot_start, "size": boot_size},
        "root": {"start": root_start, "size": root_size},
    }, indent=2))


if __name__ == "__main__":
    main()
