#!/usr/bin/env python3
import libcalamares
import datetime
import tempfile
import os

def mount_btrfs_root(mounts, mount_point):
    for part in mounts:
        if part.get("mountPoint") == "/" and part.get("fs") == "btrfs":
            libcalamares.utils.mount(part.get("device"), mount_point, "btrfs", "subvolid=5")
            break

subvolumes = {
    '@': '/',
    '@root': '/root',
    '@srv': '/srv',
    '@cache': '/var/cache',
    '@log': '/var/log',
    '@tmp': '/var/tmp',
    '@home': '/home',
}

def pretty_name():
    return "Preparing In-Place Reinstallation"
def run():
    mounts = libcalamares.job.configuration["mounts"]
    # Write mounts to the global storage directly
    libcalamares.globalstorage.insert("partitions", mounts)
    
    # Mount the root partition now
    mount_point = tempfile.mkdtemp(prefix="calamares-inplace-")
    mount_btrfs_root(mounts, mount_point)
        
    subvolume_basename = '_backup_' + datetime.datetime.now().strftime("%Y%d%m%H%M%S")
    # Rename existing subvolumes
    for subvol, path in subvolumes.items():
        subvol_name = f"{subvol}{subvolume_basename}"
        subvol_path = os.path.join(mount_point, subvol_name)
        original_subvol_path = os.path.join(mount_point, subvol)
        os.rename(original_subvol_path, subvol_path)

    libcalamares.globalstorage.insert("firmwareType", "efi")
    libcalamares.globalstorage.insert("efiSystemPartition", "/boot/efi")
    libcalamares.globalstorage.insert("garudaInplaceBtrfsRoot", mount_point)
    libcalamares.globalstorage.insert("garudaInplaceHome", f"@home{subvolume_basename}")
    libcalamares.globalstorage.insert("garudaInplaceSnapshots", f"@{subvolume_basename}/.snapshots")