Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

# Verify Admin Rights
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole]::Administrator)) {
    [System.Windows.Forms.MessageBox]::Show("Restarting as Administrator...")
    Start-Process powershell "-ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
    exit
}

function Write-Log {
    param ($text)
    $outputBox.AppendText("$text`r`n")
    $outputBox.ScrollToCaret()
}

function Stop-Unity {
    Write-Log "Stopping unity.exe and cabinet.exe if running..."
    try {
        Stop-Process -Name "unity" -Force -ErrorAction Stop
        Write-Log "unity.exe process stopped."
    } catch {
        Write-Log "unity.exe was not running or could not be stopped."
    }

    try {
        Stop-Process -Name "cabinet" -Force -ErrorAction Stop
        Write-Log "cabinet.exe process stopped."
    } catch {
        Write-Log "cabinet.exe was not running or could not be stopped."
    }
}

function Update-StartBat {
    param ([string]$Mode)

    $batPath = "C:\\pilotgames\\start.bat"

    if ($Mode -eq "Portrait") {
        $content = @"
cd /D C:\pilotgames\NDGDRelease
powershell -command "Start-Process cabinet.exe -Verb runas -ArgumentList '-screen-height', '1920', '-screen-width','1080', '-screen-fullscreen', '0', '-popupwindow'"
"@
    } else {
        $content = @"
cd /D C:\pilotgames\BRGDRelease
powershell -command "Start-Process cabinet.exe -Verb runas -ArgumentList '-screen-height', '1080', '-screen-width','1920', '-screen-fullscreen', '0', '-popupwindow'"
"@
    }

    Write-Log "Updating start.bat for $Mode..."
    Set-Content -Path $batPath -Value $content -Force -Encoding ASCII
    Write-Log "start.bat updated."
}

function Install-Pilot {
    param ([string]$Mode)

    $outputBox.Clear()
    Write-Log "Starting $Mode installation..."

    if ($Mode -eq "Portrait") {
        $zipFile = "NDGDRelease-2025.08.07.1.zip"
		$orient = "Portrait"
    } else {
        $zipFile = "NDGDRelease-2025.06.17.1.zip"
		$orient = "Dual"
    }

    Write-Log "`nRenaming PC using MAC address..."
    $mac = (Get-NetAdapter -InterfaceAlias "*Ethernet*" | Select-Object -First 1 -ExpandProperty MacAddress) -replace '-', ''
    if ($mac) {
        Rename-Computer -NewName "$mac" -Force
        Write-Log "Computer renamed to: $mac"
        Write-Log "Please restart the computer to apply the change.`n"
    } else {
        Write-Log "Could not retrieve MAC address.`n"
    }

    Write-Log "Stopping PilotGameAgent service..."
    Stop-Service -Name "PilotGameAgent" -Force -ErrorAction SilentlyContinue

    Stop-Unity

    pushd "C:\\pilotgames"

    Write-Log "Clearing downloads folder..."
    Remove-Item -Path "C:\\pilotgames\\downloads\\*" -Force -Recurse -ErrorAction SilentlyContinue

    Write-Log "Removing backup folders..."
    Remove-Item -Path "C:\\pilotgames\\BRGDRelease.bak" -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "C:\\pilotgames\\NDGDRelease.bak" -Recurse -Force -ErrorAction SilentlyContinue

    Write-Log "Waiting 10 seconds..."
    Start-Sleep -Seconds 10

    if (Test-Path "C:\\pilotgames\\BRGDRelease") {
        Write-Log "Backing up BRGDRelease folder..."
        Move-Item "C:\\pilotgames\\BRGDRelease" "C:\\pilotgames\\BRGDRelease.bak" -Force
    }
    if (Test-Path "C:\\pilotgames\\NDGDRelease") {
        Write-Log "Backing up NDGDRelease folder..."
        Move-Item "C:\\pilotgames\\NDGDRelease" "C:\\pilotgames\\NDGDRelease.bak" -Force
    }

    Write-Log "Copying release zip file..."
    $zipPath = "C:\\pilotDownloads\\$orient\\$zipFile"
    Copy-Item -Path $zipPath -Destination "C:\\pilotgames\\downloads\\" -Force

    Write-Log "Unzipping file into C:\\pilotgames..."
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipPath, "C:\\pilotgames")

    Update-StartBat -Mode $Mode

    Write-Log "Waiting 20 seconds..."
    Start-Sleep -Seconds 20

    Write-Log "Starting PilotGameAgent service..."
    Set-Service -Name "PilotGameAgent" -StartupType Automatic -PassThru
    Start-Service -Name "PilotGameAgent"

    Write-Log "$Mode installation completed successfully."
}

function Set-HighPerformancePowerPlan {
    Write-Log "`nActivating High Performance power plan..."
    $highPerf = powercfg -l | Where-Object { $_ -match "High performance" -or $_ -match "Alto desempenho" }
    if ($highPerf) {
        $guid = ($highPerf -split '\s+')[3]
        powercfg -setactive $guid

        powercfg -change -monitor-timeout-ac 0
        powercfg -change -monitor-timeout-dc 0
        powercfg -change -standby-timeout-ac 0
        powercfg -change -standby-timeout-dc 0
        powercfg -change -disk-timeout-ac 0
        powercfg -change -disk-timeout-dc 0

        Write-Log "Power settings applied successfully.`n"
    } else {
        Write-Log "High Performance power plan not found.`n"
    }
}

function Rename-PCToMac {
    Write-Log "`nRenaming PC using MAC address..."
    $mac = (Get-NetAdapter -InterfaceAlias "*Ethernet*" | Select-Object -First 1 -ExpandProperty MacAddress) -replace '-', ''
    if ($mac) {
        Rename-Computer -NewName "$mac" -Force
        Write-Log "Computer renamed to: $mac"
        Write-Log "Please restart the computer to apply the change.`n"
    } else {
        Write-Log "Could not retrieve MAC address.`n"
    }
}

function Install-CommonTools {
    Write-Log "`nInstalling tools and dependencies via winget..."
    try {
        winget install -e --id Notepad++.Notepad++ --accept-source-agreements --accept-package-agreements
        winget install -e --id Microsoft.DotNet.DesktopRuntime.8 --accept-source-agreements --accept-package-agreements
        winget install -e --id Microsoft.VCRedist.2015+.x64 --accept-source-agreements --accept-package-agreements
        Write-Log "Installation completed.`n"
    } catch {
        Write-Log "Installation error: $_"
    }
}

function Disable-UACAndNotifications {
    Write-Log "`nDisabling UAC and notifications..."
    try {
        Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 0
        Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 0
        New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender Security Center\Notifications" -Force | Out-Null
        Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender Security Center\Notifications" -Name "DisableEnhancedNotifications" -Type DWord -Value 1
        Set-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search -Name SearchBoxTaskbarMode -Value 0 -Type DWord -Force
        Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
        Write-Log "UAC and notifications disabled.`n"
    } catch {
        Write-Log "Error while configuring system: $_"
    }
}

# GUI
$form = New-Object System.Windows.Forms.Form
$form.Text = "Pilot Installer"
$form.Size = New-Object System.Drawing.Size(600,500)
$form.StartPosition = "CenterScreen"

$buttons = @(
    @{ Text = "Install Portrait"; Action = { Install-Pilot -Mode "Portrait" } },
    @{ Text = "Install Dual"; Action = { Install-Pilot -Mode "Dual" } },
    @{ Text = "Exit"; Action = { $form.Close() } }
)

$x = 10
foreach ($btn in $buttons) {
    $button = New-Object System.Windows.Forms.Button
    $button.Text = $btn.Text
    $button.Size = New-Object System.Drawing.Size(140,30)
    $button.Location = New-Object System.Drawing.Point($x,20)
    $button.Add_Click($btn.Action)
    $form.Controls.Add($button)
    $x += 150
}

$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Multiline = $true
$outputBox.ScrollBars = "Vertical"
$outputBox.ReadOnly = $true
$outputBox.Size = New-Object System.Drawing.Size(560,370)
$outputBox.Location = New-Object System.Drawing.Point(10,70)
$outputBox.Font = New-Object System.Drawing.Font("Consolas",10)
$outputBox.Name = "OutputTextBox"

$form.Controls.Add($outputBox)
$form.Topmost = $true
$form.ShowDialog()
