$env:WIN_COMPUTER_NAME = "DerGeret";
$env:SETUP_SCRIPT_NAME = [System.IO.Path]::GetRelativePath("$PSScriptRoot/../../..", "$PSScriptRoot/Restore.ps1");

$Global:SetupConfigPostprocessor = {
    param([xml] $config, [System.Xml.XmlNamespaceManager] $namespace)

    $setupComponent = $config.SelectSingleNode(
        "/ua:unattend/ua:settings[@pass='windowsPE']/ua:component[@name='Microsoft-Windows-Setup']",
        $namespace);

    $diskConfig = $setupComponent.SelectSingleNode("./ua:DiskConfiguration/ua:Disk", $namespace);
    $installationPartition = $setupComponent.SelectSingleNode("./ua:ImageInstall/ua:OSImage/ua:InstallTo/ua:PartitionID", $namespace);

    $newIndex = [int]$installationPartition.InnerText;
    $installationPartition.InnerText = "$($newIndex + 1)";
    $partitionCreations = $diskConfig.SelectSingleNode("./ua:CreatePartitions", $namespace);
    $newPartition = $partitionCreations.SelectNodes("./ua:CreatePartition", $namespace)[0].CloneNode($true);

    $offset = 0;

    for ($i = 0; $i -lt $partitionCreations.ChildNodes.Count; $i++) {
        $partition = $partitionCreations.ChildNodes[$i];
        $order = [int]$partition.SelectSingleNode("./ua:Order", $namespace).InnerText;

        if ($order -ge $newIndex) {
            $partition.SelectSingleNode("./ua:Order", $namespace).InnerText = "$($order + 1)";
        } else {
            $offset += [int]$partition.SelectSingleNode("./ua:Size", $namespace).InnerText;
        }
    }

    # Add 1 TB space before Windows installation... wha-!? For Linux, ofc! I use Arch Linux, btw.
    $newPartition.SelectSingleNode("./ua:Size", $namespace).InnerText = "$((1 * 1024 * 1024) - $offset)";
    $newPartition.SelectSingleNode("./ua:Order", $namespace).InnerText = "$newIndex";

    $null = $partitionCreations.AppendChild($newPartition);

    $partitionModifications = $diskConfig.SelectSingleNode("./ua:ModifyPartitions", $namespace);
    $newModification = $partitionModifications.SelectNodes("./ua:ModifyPartition", $namespace)[2].CloneNode($true);
    $newModification.SelectSingleNode("./ua:Order", $namespace).InnerText = "$newIndex";
    $newModification.SelectSingleNode("./ua:PartitionID", $namespace).InnerText = "$newIndex";

    for ($i = 0; $i -lt $partitionModifications.ChildNodes.Count; $i++) {
        $partition = $partitionModifications.ChildNodes[$i];
        $partitionID = [int]$partition.SelectSingleNode("./ua:PartitionID", $namespace).InnerText;

        if ($partitionID -ge $newIndex) {
            $partition.SelectSingleNode("./ua:PartitionID", $namespace).InnerText = "$($partitionID + 1)";
            $partition.SelectSingleNode("./ua:Order", $namespace).InnerText = "$($partitionID + 1)";
        }
    }

    $null = $partitionModifications.AppendChild($newModification);
}

. "$PSScriptRoot/../../../scripts/Windows/OS/Setup.ps1";