#!/usr/bin/env python3
import os
import subprocess

def run_command(command):
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return result.stdout.decode().strip()

def main():
    # No registrar los errores.
    os.environ["DEBUG"] = "no"

    ser = run_command("ogGetSerialNumber")
    cfg = ""
    disks = int(run_command("ogDiskToDev | wc -w"))

    for dsk in range(1, disks + 1):
        particiones = run_command(f"ogGetPartitionsNumber {dsk}")
        particiones = int(particiones) if particiones else 0
        ptt = run_command(f"ogGetPartitionTableType {dsk}")

        ptt_map = {
            "MSDOS": 1,
            "GPT": 2,
            "LVM": 3,
            "ZPOOL": 4
        }
        ptt = ptt_map.get(ptt, 0)

        cfg += f"{dsk}:0:{ptt}:::{run_command(f'ogGetDiskSize {dsk}')}:0;"

        for par in range(1, particiones + 1):
            cod = run_command(f"ogGetPartitionId {dsk} {par} 2>/dev/null")
            fsi = run_command(f"getFsType {dsk} {par} 2>/dev/null") or "EMPTY"
            tam = run_command(f"ogGetPartitionSize {dsk} {par} 2>/dev/null") or "0"
            soi = ""
            uso = 0

            if fsi not in ["", "EMPTY", "LINUX-SWAP", "LINUX-LVM", "ZVOL"]:
                if run_command(f"ogMount {dsk} {par} 2>/dev/null"):
                    soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1]
                    if not soi:
                        soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1]
                    if not soi and fsi not in ["EMPTY", "CACHE"]:
                        soi = "DATA"
                    uso = int(run_command(f"df $(ogGetMountPoint {dsk} {par}) | awk '{{getline; printf \"%d\",$5}}'") or 0)
                else:
                    soi = ""
                    uso = 0

            cfg += f"{dsk}:{par}:{cod}:{fsi}:{soi}:{tam}:{uso};"

    if not cfg:
        cfg = "1:0:0:::0;"

    cfgfile = "/tmp/getconfig"
    with open(cfgfile, "w") as f:
        f.write(f"{ser + ';' if ser else ''}{cfg}")

    run_command("generateMenuDefault &>/dev/null")

    with open(cfgfile, "r") as f:
        data = f.read()

    lines = data.split(";")
    for line in lines:
        if line:
            parts = line.split(":")
            if len(parts) == 1:
                print(f"ser={parts[0]}")
            else:
                print(f"disk={parts[0]}\tpar={parts[1]}\tcpt={parts[2]}\tfsi={parts[3]}\tsoi={parts[4]}\ttam={parts[5]}\tuso={parts[6]}")

    run_command("rm -f /mnt/*/ogboot.* /mnt/*/*/ogboot.*")

    # Volver a registrar los errores.
    os.environ.pop("DEBUG", None)

if __name__ == "__main__":
    main()
