# -----------------------------------------------
# Elevate script if not running as Administrator
# ---------------------------------------------------
if (-not ([Security.Principal.WindowsPrincipal] `
          [Security.Principal.WindowsIdentity]::GetCurrent() `
          ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {

    Start-Process powershell `
        -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" `
        -Verb RunAs
    exit
}

# Force normal PowerShell colors after elevation
try {
    $Host.UI.RawUI.BackgroundColor = 'Black'
    $Host.UI.RawUI.ForegroundColor = 'White'
    Clear-Host
} catch {}

# ------------
# Load Config
# ----------------
# Get the parent folder of the currently running script
$ProjectRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)

# Check if "scripts\config" exists
$ScriptConfigPath1up = Join-Path $ProjectRoot "scripts\config"
$ScriptConfigPath2up = Join-Path $ProjectRoot "config"

if (Test-Path $ScriptConfigPath1up) {
    # If Scripts\Config exists
    $ConfigFile = Join-Path $ScriptConfigPath1up "config.ps1"
} elseif (Test-Path $ScriptConfigPath2up) {
    # If \Config exists
    $ConfigFile = Join-Path $ScriptConfigPath2up "config.ps1"
} else {
    throw "Could not find Config.ps1!"
}

# Dot-source the config
. $ConfigFile

$ConfigPath = Split-Path -Parent $ConfigFile
$Script  = Split-Path $PSCommandPath -Leaf

# Disable QuickEdit for this session
. "$ConfigPath\DisableConsoleQuickEdit.ps1"
Set-QuickEdit -DisableQuickEdit
cls

# --------------------
# Display Main Banner
# ------------------------
Write-Host ""
Write-Host "============================================================" -ForegroundColor DarkGray
Write-Host " RMTechCentral Automation Scripts (v$($ReleaseInfo.Version))" -ForegroundColor Cyan

switch ($Global:ReleaseInfo.Channel) {
    'Internal' {
        Write-Host " Internal Use Only" -ForegroundColor Yellow
    }
    'Public' {
        Write-Host " Public Release" -ForegroundColor Green
    }
    default {
        Write-Host " Release Channel: $($Global:ReleaseInfo.Channel)" -ForegroundColor DarkYellow
    }
}

Write-Host "============================================================" -ForegroundColor DarkGray
Write-Host " Author:  $($RMTechMeta.Author)" -ForegroundColor Gray
Write-Host " Website: $($RMTechMeta.Website)" -ForegroundColor Gray
Write-Host " Purpose: $($RMTechMeta.Purpose)" -ForegroundColor Gray
Write-Host "============================================================" -ForegroundColor DarkGray
Write-Host ""

# Small delay so user can read
Start-Sleep -Seconds 2
Write-Host "$Script running as: $($RMTechMeta.User) on $($RMTechMeta.Machine)" -ForegroundColor DarkGray
Write-Host ""
Write-Host ""

# Small delay so user can read
Start-Sleep -Seconds 3
# Display Pending Operation
Write-Host "==================================================================" -ForegroundColor DarkGray
Write-Host " Pending Operation: Initialize and rebuild Windows image workspace" -ForegroundColor DarkGreen
Write-Host " Review this step carefully. Close this window to cancel." -ForegroundColor Yellow
Write-Host "==================================================================" -ForegroundColor DarkGray
Write-Host ""

# Wait for user to confirm
Write-Host "Press ENTER to continue..." -ForegroundColor Gray
Read-Host

# -----------
# Run Script
# ---------------
# Unmount WIM if mounted
Write-Host ""
Write-Host "Checking if WIM is mounted ..." -ForegroundColor Cyan
Start-Sleep -Seconds 2
if (Test-Path (Join-Path $Paths.WIMMountRoot "Windows")) {
    # Attemp WIM mount folder/file cleanup
	Write-Host ""
	Write-Host "Unmounting WIM ..." -ForegroundColor Cyan
	Remove-Item "$($Paths.WIMMountRoot)\*" -Recurse -Force -ErrorAction SilentlyContinue

	# Unmount/Cleanup Wim and commit changes
	dism /Unmount-Wim /MountDir:"$($Paths.WIMMountRoot)" /Discard
	dism /cleanup-wim

	#Unload additional registry hives
	$Core = "SAM|SECURITY|SOFTWARE|SYSTEM|HARDWARE|BCD00000000"

	reg query HKLM | ForEach-Object {
		if ($_ -match "HKEY_LOCAL_MACHINE\\(.+)$") {
			$Name = $Matches[1]
			if ($Name -notmatch "^($Core)$") {
				Write-Host "Unloading HKLM\$Name"
				reg unload "HKLM\$Name" 2>$null
			}
		}
	}

	# Attemp WIM mount folder/file cleanup second round
	Remove-Item "$($Paths.WIMMountRoot)\*" -Recurse -Force -ErrorAction SilentlyContinue
	}
	
# Log WIM mounted/unmounted status to $Paths.ScriptsRoot
$MountedLog   = Join-Path $Paths.ScriptsRoot "WIM-Mounted.log"
$UnmountedLog = Join-Path $Paths.ScriptsRoot "WIM-Unmounted.log"

if (Test-Path (Join-Path $Paths.WIMMountRoot "Windows")) {
    Remove-Item -Path $UnmountedLog -ErrorAction SilentlyContinue
    New-Item -Path $MountedLog -ItemType File -Force | Out-Null
}
else {
    Remove-Item -Path $MountedLog -ErrorAction SilentlyContinue
    New-Item -Path $UnmountedLog -ItemType File -Force | Out-Null
}

# Clear target directories
Write-Host ""
Write-Host "Clearing ISO_Extracted and WIM_Extracted\Mount directories ..." -ForegroundColor Cyan
foreach ($dir in @($Paths.WIMSourceRoot, $Paths.ISOExtracted)) {
    if (-not (Test-Path $dir)) {
        New-Item -Path $dir -ItemType Directory -Force | Out-Null
    }

    # Remove all contents inside the folder (but keep the folder)
    Get-ChildItem -Path $dir -Force -ErrorAction SilentlyContinue |
        Remove-Item -Recurse -Force -ErrorAction Stop
}

# Resolve the ISO file to use
Write-Host ""
Write-Host "Locating ISO ..." -ForegroundColor Cyan

$isoFolder = $Paths.GoldISOSource
$iso = Get-ChildItem -Path $isoFolder -Filter *.iso -File -ErrorAction SilentlyContinue

if (-not $iso) {
    Write-Host ""
    Write-Host "ERROR: No ISO file was found." -ForegroundColor Red
    Write-Host "Expected location:" -ForegroundColor Red
    Write-Host "  $isoFolder" -ForegroundColor Red
    Write-Host ""
    Write-Host "A valid Windows ISO is required to continue." -ForegroundColor Red
    Write-Host ""
    Read-Host "Press ENTER to exit"
    exit 1
}
elseif ($iso.Count -gt 1) {
    Write-Host ""
    Write-Host "ERROR: Multiple ISO files were found." -ForegroundColor Red
    Write-Host "Only one ISO is allowed in:" -ForegroundColor Red
    Write-Host "  $isoFolder" -ForegroundColor Red
    Write-Host ""
    Read-Host "Press ENTER to exit"
    exit 1
}

$isoPath = $iso.FullName
Write-Host ""
Write-Host "Using ISO: $($iso.Name)" -ForegroundColor Cyan

# Mount ISO and copy contents
$mounted = $null
try {
	Write-Host ""
    Write-Host "Mounting ISO..." -ForegroundColor Cyan
    $mounted = Mount-DiskImage -ImagePath $isoPath -PassThru -ErrorAction Stop

    $vol = $mounted | Get-Volume -ErrorAction Stop
    $isoDrive = ($vol.DriveLetter + ":\")
    if (-not (Test-Path $isoDrive)) {
        throw "Mounted ISO drive letter not accessible."
    }
    Write-Host ""
    Write-Host "Mounted at $isoDrive" -ForegroundColor Green
	
	Write-Host ""
	Write-Host "Defaulting ISO_Extracted directory ..." -ForegroundColor Cyan
    #$null = robocopy $isoDrive $Paths.ISOExtracted /MIR /R:2 /W:2 /NFL /NDL /NP
     $null = robocopy $isoDrive $Paths.ISOExtracted /MIR /A-:R /R:2 /W:2 /NFL /NDL /NP
    if ($LASTEXITCODE -ge 8) {
        throw "Robocopy failed with exit code $LASTEXITCODE"
    }
}
finally {
    if ($mounted) {
		Write-Host ""
	    Write-Host "Unmounting ISO ..." -ForegroundColor Cyan
        Dismount-DiskImage -ImagePath $isoPath -ErrorAction SilentlyContinue
    }
}

# Copy persistent data to ISO_Extracted
Write-Host ""
Write-Host "Copying persistent data to ISO_Extracted ..." -ForegroundColor Cyan
Copy-Item -Path (Join-Path $Paths.ISOPersistent '*') `
    -Destination $Paths.ISOExtracted `
    -Recurse -Force
Start-Sleep -Seconds 1

# Copy install.wim -> WIMSourceRoot
$installWim = Join-Path $Paths.ISOExtracted "sources\install.wim"
if (-not (Test-Path $installWim)) {
    throw "install.wim not found at $installWim"
}
Write-Host ""
Write-Host "Defaulting WIM_Extracted\Mount directory ..." -ForegroundColor Cyan
Copy-Item -Path $installWim -Destination $Paths.WIMSourceRoot -Force
Start-Sleep -Seconds 1

# -------
# Finish
# -----------
Write-Host ""
Write-Host ""
Write-Host ""
Write-Host "=========================================================================" -ForegroundColor DarkGray
Write-Host " [DONE] Operation complete!" -ForegroundColor Green
Write-Host " Please review the output above for any warnings or errors before exiting." -ForegroundColor Yellow
Write-Host "=========================================================================" -ForegroundColor DarkGray
Write-Host ""

# Wait for user to confirm
Write-Host "Press ENTER to quit..." -ForegroundColor Gray
Read-Host
