$ErrorActionPreference = "Stop"

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$pluginName = "Pioneer MP Trigger.vst3"
$pluginSource = Join-Path $scriptDir $pluginName
$vst3Root = Join-Path $env:ProgramFiles "Common Files\VST3"
$pluginDest = Join-Path $vst3Root $pluginName

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 MP Trigger 0.9.1 VST3 installer"
Write-Host ""

if (-not (Test-Path -LiteralPath $pluginSource)) {
    throw "Cannot find $pluginName 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 Common 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 $vst3Root | Out-Null

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

Copy-Item -LiteralPath $pluginSource -Destination $vst3Root -Recurse -Force

Write-Host ""
Write-Host "Installed successfully:"
Write-Host "  $pluginDest"
Write-Host ""
Write-Host "Open your DAW and rescan VST3 plug-ins if it does not appear automatically."
