# Check for admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "ERROR: This script must be run as Administrator" -ForegroundColor Red
    Read-Host "Press Enter to exit"
    Exit 1
}

# Remove all user data before proceeding
Write-Host "Cleaning user data..."

# Remove all user profiles except system accounts
$systemAccounts = @('Public', 'Default', 'Default User', 'All Users', 'defaultuser0')
$currentUser = $env:USERNAME

Get-ChildItem C:\Users | Where-Object {
    $_.PSIsContainer -and 
    $systemAccounts -notcontains $_.Name -and
    $_.Name -ne $currentUser
} | ForEach-Object {
    try { Remove-Item $_.FullName -Recurse -Force -ErrorAction Stop } catch { Write-Host "Error removing $($_.FullName): $_" -ForegroundColor Red }
}

# Clean current user's data folders (if running from audit mode admin account)
$foldersToClean = @('Desktop', 'Downloads', 'Documents', 'Pictures', 'Videos', 'Music')
foreach ($folder in $foldersToClean) {
    $path = "$env:USERPROFILE\$folder\*"
    try { Remove-Item $path -Recurse -Force -ErrorAction Stop } catch { Write-Host "Error cleaning $path : $_" -ForegroundColor Red }
}

# Clear temp files
try { Remove-Item C:\Windows\Temp\* -Recurse -Force -ErrorAction Stop } catch { Write-Host "Error clearing Windows Temp: $_" -ForegroundColor Red }
try { Remove-Item C:\Users\*\AppData\Local\Temp\* -Recurse -Force -ErrorAction Stop } catch { Write-Host "Error clearing user Temp: $_" -ForegroundColor Red }

# Remove user registry entries
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" | Where-Object {
    $sid = $_.PSChildName
    $sid -match '^S-1-5-21-' -and $sid -notmatch '\.bak$'
} | ForEach-Object {
    $profilePath = (Get-ItemProperty $_.PSPath).ProfileImagePath
    if ($profilePath -and !(Test-Path $profilePath)) {
        try { Remove-Item $_.PSPath -Recurse -ErrorAction Stop } catch { Write-Host "Error removing registry $($_.PSPath): $_" -ForegroundColor Red }
    }
}

Write-Host "User data cleanup complete."

Write-Host "Running Installation script v4.0"

#Determining drive letter with installation files
$validPath = $false
while (-not $validPath) {
    $DriveLetter = Read-Host "Drive with installation files? (Leave empty to download from internet)"
    
    if (-not $DriveLetter) {
        Write-Host "No drive specified. Will download from unzipped.mec-consult.org/Unzipped.tar"
        $validPath = $true
    } else {
        $DriveLetter = $DriveLetter.ToUpper()
        if (Test-Path "${DriveLetter}:\Unzipped.tar") {
            $validPath = $true
            try { $windowsISO = Get-ChildItem "${DriveLetter}:\ISO\Win*.iso" -ErrorAction Stop | Select-Object -First 1 } catch { Write-Host "No Windows ISO found: $_" -ForegroundColor Red }
        } else {
            Write-Host "Invalid drive: ${DriveLetter}:\Unzipped.tar not found. Please try again." -ForegroundColor Yellow
        }
    }
}

# Check Windows version
if ($windowsISO) {
    $currentVersion = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").DisplayVersion
    Write-Host "Current Windows version: $currentVersion"
    Write-Host "Found Windows ISO: $($windowsISO.Name)"
    
    if ($windowsISO.Name -match $currentVersion) {
        Write-Host "Already on $currentVersion. No upgrade needed." -ForegroundColor Green
    } else {
        $isoVersion = if ($windowsISO.Name -match '(\d{2}H\d)') { $matches[1] } else { "newer version" }
        Write-Host "Current version: $currentVersion. Upgrade to $isoVersion available. Please upgrade later." -ForegroundColor Yellow
    }
} else {
    Write-Host "No Windows ISO found" -ForegroundColor Yellow
}

# Turning off Windows Defender
Write-Host "Disabling Windows Defender"
$defenderDisabled = $false
while (-not $defenderDisabled) {
    try {
        Set-MpPreference -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableRealtimeMonitoring $true -DisableScriptScanning $true -EnableControlledFolderAccess Disabled -EnableNetworkProtection AuditMode -Force -MAPSReporting Disabled -SubmitSamplesConsent NeverSend -ErrorAction Stop
        
        $prefs = Get-MpPreference
        if ($prefs.DisableRealtimeMonitoring -eq $true) {
            Write-Host "Windows Defender disabled successfully" -ForegroundColor Green
            $defenderDisabled = $true
        } else {
            throw "Real-time monitoring still enabled"
        }
    } catch {
        Write-Host "Windows Defender is still enabled. Please disable Tamper Protection." -ForegroundColor Yellow
        Start-Process "windowsdefender://threatsettings"
        Read-Host "Press Enter after disabling Tamper Protection to retry"
    }
}

# Extract/copy files
if ($DriveLetter) {
    Write-Host "Extracting files from drive"
    tar -xf "${DriveLetter}:\Unzipped.tar" -C C:\
} else {
    Write-Host "Downloading and extracting files"
    Start-BitsTransfer -Source "http://unzipped.mec-consult.org/Unzipped.tar" -Destination "$env:TEMP\Unzipped.tar" -Description "Downloading installation files"
    tar -xf "$env:TEMP\Unzipped.tar" -C C:\
    Remove-Item "$env:TEMP\Unzipped.tar"
}

# Backup installation script to Unzipped folder
Write-Host "Backing up installation script"
Invoke-WebRequest -Uri "https://installation.mec-consult.org" -OutFile "C:\Unzipped\installation.ps1" -UseBasicParsing

# Run EXE installers in parallel
Write-Host "Starting EXE installers in parallel"

# 1. ArcGIS Part 1 (EXE)
Write-Host "ArcGIS 10.8: Starting Installation (Part 1)"
Start-Process 'C:\Unzipped\ESRI ArcGIS Desktop 10.8\ESRI ArcGIS Desktop 10.8\ArcGIS_Desktop_108_172737.exe' "/S" -Wait

# Now start Part 2 and other EXEs in parallel
Write-Host "ArcGIS 10.8: Starting Installation (Part 2)"
$arcgis2 = Start-Process $env:USERPROFILE'\Documents\ArcGIS 10.8\Desktop\Setup.exe' "/passive /norestart" -PassThru -ErrorAction Stop

# 3. Global Mapper (EXE)
Write-Host "Global Mapper: Starting Installation"
$globalmapper = Start-Process 'C:\Unzipped\Global Mapper 22.1.0 Build 021721 incl patch [CrackingPatching]\global-mapper-22_1-x64.exe' "/S" -PassThru -ErrorAction Stop

# 6. Envi (EXE)
Write-Host "Envi: Starting Installation"
$envi = Start-Process 'C:\Unzipped\Envi 5.6\envi56-win.exe' "/Silent" -PassThru -ErrorAction Stop

# Wait for EXE installers to complete
Write-Host "Waiting for EXE installers to complete"
$arcgis2, $globalmapper, $envi | Where-Object { $_ -ne $null } | Wait-Process

# Adobe (EXE - but uses Windows Installer backend, run separately)
Write-Host "Adobe Acrobat Pro: Starting Installation"
$mountResult = Mount-DiskImage 'C:\Unzipped\Adobe.Acrobat.Pro.2023.u2.x64.Multilingual.iso' -PassThru -ErrorAction Stop
Start-Sleep -Seconds 5
$driveLetter = (Get-DiskImage 'C:\Unzipped\Adobe.Acrobat.Pro.2023.u2.x64.Multilingual.iso' | Get-Volume).DriveLetter
Start-Process "$($driveLetter):Adobe Acrobat Pro\setup.exe" "/sPB /rps" -Wait -ErrorAction Stop

# Now run MSI installers sequentially
Write-Host "Starting MSI installers (sequential)"

# 2. Agisoft (MSI)
Write-Host "Agisoft: Starting Installation"
Start-Process 'C:\Unzipped\Agisoft Metashape Professional 1.8.4 Build 14493 (x64) Multilingual\metashape-pro_1_8_4_x64.msi' "/passive /norestart" -Wait -ErrorAction Stop

# 5. Nitro (MSI)
Write-Host "Nitro: Starting Installation"
Start-Process 'C:\Unzipped\Nitro Pro 14.5.0.11 (x64) Enterprise + Crack\Setup\nitro_pro14_x64.msi' "/passive /norestart" -Wait -ErrorAction Stop

Write-Host "All installations complete"

# Now apply cracks/patches
Write-Host "Applying cracks and patches"

# 1.3.1 Moving activation files for ArcGIS 10.8
Write-Host "ArcGIS 10.8: Copying files over"
Copy-Item -Path 'C:\Unzipped\ESRI ArcGIS Desktop 10.8\ESRI ArcGIS Desktop 10.8\Crack\AfCore.dll' 'C:\Program Files (x86)\ArcGIS\Desktop10.8\bin'

# 2.2 Activating Agisoft
Write-Host "Agisoft: Activating"
Start-Process 'C:\Unzipped\Agisoft Metashape Professional 1.8.4 Build 14493 (x64) Multilingual\crack\Patch.exe' -ArgumentList "/S" -Wait

# 3.2 Copying activation files for Global Mapper
Write-Host "Global Mapper: Copying activation files"
Copy-Item -Path 'C:\Unzipped\Global Mapper 22.1.0 Build 021721 incl patch `[CrackingPatching`]\patch\x64\global_mapper.exe' -Destination 'C:\Program Files\GlobalMapper22.1_64bit\' -Force
Copy-Item -Path 'C:\Unzipped\Global Mapper 22.1.0 Build 021721 incl patch `[CrackingPatching`]\patch\x64\ProgramData\GlobalMapper\' -Destination 'C:\ProgramData\' -Recurse

# 4.2 Activating Adobe Acrobat Pro
Write-Host "Adobe Acrobat Pro: Activating"
try { Start-Process "$($driveLetter):Adobe Acrobat Pro\crack.exe" "/S" -Wait -ErrorAction Stop } catch { Write-Host "Error activating Adobe: $_" -ForegroundColor Red }
# 4.3 Disabling Adobe's Auto Update Service
Stop-Service 'AdobeARMservice'
# 4.4 Dismounting ISO file
Dismount-DiskImage 'C:\Unzipped\Adobe.Acrobat.Pro.2023.u2.x64.Multilingual.iso'

# 5.2 Copying activation files for Nitro
Copy-Item -Path 'C:\Unzipped\Nitro Pro 14.5.0.11 (x64) Enterprise + Crack\Crack\NitroPDF.exe' -Destination 'C:\Program Files\Nitro\PDF Pro\14' -Force

# 6.2 Moving activation files for Envi
Copy-Item -Path 'C:\Unzipped\Envi 5.6\Crack 5.6\x86bit\*' -Destination 'C:\Program Files\Harris\ENVI56\IDL88\bin\bin.x86\' -Force
Copy-Item -Path 'C:\Unzipped\Envi 5.6\Crack 5.6\x64bit\*' -Destination 'C:\Program Files\Harris\ENVI56\IDL88\bin\bin.x86_64\' -Force

try {
    $version = winget --version
    Write-Output "Winget is installed. Version: $version"
} catch {
    Write-Output "Winget is not installed. Installing now"
    Invoke-WebRequest -Uri "https://aka.ms/getwinget" -OutFile "$env:TEMP\AppInstaller.appxbundle"
    Start-Process -FilePath "$env:TEMP\AppInstaller.appxbundle" -Wait
    Write-Output "Winget installation completed."
}

# Reset winget sources to fix certificate error
winget source remove msstore

# Installing other programs via winget (using winget source only)
$listOfPrograms = "Bitdefender.Bitdefender", "Google.Chrome", "Mozilla.Firefox", "mcmilk.7zip-zstd", "RustDesk.RustDesk", "Google.EarthPro", "Zoom.Zoom"
foreach ($program in $listOfPrograms) { winget install -h -e --id $program --source winget }

# Configure RustDesk with custom server
Write-Host "Configuring RustDesk"
$rustdesk_cfg = "id=rustdesk.thineswar.com,key=lVrmcr3T6SBqNdSJldbYbb7XUvhZqqvGUB4G2i+Q3cg="
$rustdesk_pw = (-join ((65..90) + (97..122) | Get-Random -Count 12 | % {[char]$_}))

Start-Sleep -Seconds 10

$ServiceName = 'Rustdesk'
$arrService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue

while ($arrService -eq $null) {
    Write-Host "Waiting for RustDesk service to be installed..."
    Start-Sleep -Seconds 5
    $arrService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
}

while ($arrService.Status -ne 'Running') {
    Start-Service $ServiceName
    Start-Sleep -Seconds 5
    $arrService.Refresh()
}

while (-not (Test-Path "$env:ProgramFiles\RustDesk\rustdesk.exe")) {
    Write-Host "Waiting for RustDesk executable..."
    Start-Sleep -Seconds 5
}

cd "$env:ProgramFiles\RustDesk"
.\rustdesk.exe --config $rustdesk_cfg
.\rustdesk.exe --password $rustdesk_pw

Write-Host "RustDesk configured successfully" -ForegroundColor Green

# Pin cracked apps to prevent upgrades
Write-Host "Pinning cracked applications"
winget pin add --id Agisoft.Metashape.Professional
winget pin add --id Adobe.Acrobat.Reader.64-bit

# Upgrade all installed packages
Write-Host "Upgrading all installed packages"
winget upgrade --all -h

# Deleting instalation files
Write-Host "Removing C:\Unzipped folder"
Remove-Item 'C:\Unzipped' -Recurse

# Schedule sysprep to run after reboot (to apply Windows upgrade)
Write-Host "Scheduling sysprep to run after reboot"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" -Name "Sysprep" -Value "C:\Windows\System32\Sysprep\sysprep.exe /oobe /shutdown"

# Reboot to apply Windows upgrade
Write-Host "Rebooting to apply Windows upgrade. System will run sysprep after reboot."
Restart-Computer -Force
