$ErrorActionPreference = "Stop"

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$appName = "Pioneer AD Sampler.exe"
$appSource = Join-Path $scriptDir $appName
$installRoot = Join-Path $env:ProgramFiles "Pioneer AD Sampler"
$appDest = Join-Path $installRoot $appName

function Test-IsAdministrator {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

Write-Host "Pioneer AD Sampler 0.1.0 Standalone installer"
Write-Host ""

if (-not (Test-Path -LiteralPath $appSource)) {
    throw "Cannot find $appName next to this installer script. Extract the whole ZIP archive first, then run the installer from the extracted folder."
}

if (-not (Test-IsAdministrator)) {
    Write-Host "Administrator rights are required to install into Program Files."
    Write-Host "Requesting elevation..."
    Start-Process -FilePath "powershell.exe" -ArgumentList @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $PSCommandPath) -Verb RunAs -Wait
    exit
}

New-Item -ItemType Directory -Force -Path $installRoot | Out-Null

if (Test-Path -LiteralPath $appDest) {
    Write-Host "Replacing existing installation:"
    Write-Host "  $appDest"
    Remove-Item -LiteralPath $appDest -Force
}

Copy-Item -LiteralPath $appSource -Destination $installRoot -Force

$shortcutTargets = @(
    (Join-Path ([Environment]::GetFolderPath("CommonPrograms")) "Pioneer AD Sampler\Pioneer AD Sampler.lnk"),
    (Join-Path ([Environment]::GetFolderPath("CommonDesktopDirectory")) "Pioneer AD Sampler.lnk")
)

$shell = New-Object -ComObject WScript.Shell
foreach ($shortcutPath in $shortcutTargets) {
    $shortcutDir = Split-Path -Parent $shortcutPath
    New-Item -ItemType Directory -Force -Path $shortcutDir | Out-Null

    $shortcut = $shell.CreateShortcut($shortcutPath)
    $shortcut.TargetPath = $appDest
    $shortcut.WorkingDirectory = $installRoot
    $shortcut.IconLocation = $appDest
    $shortcut.Save()
}

Write-Host ""
Write-Host "Installed successfully:"
Write-Host "  $appDest"
Write-Host "Shortcuts were added to the Start Menu and Public Desktop."
