param(
  [Parameter(Mandatory = $true)]
  [string]$RuntimeSource,
  [string]$PackageDir = $PSScriptRoot,
  [string]$InstallRoot = (Join-Path $env:LOCALAPPDATA 'PLAIS Validator')
)

$ErrorActionPreference = 'Stop'
$configPath = Join-Path $PackageDir 'node-config.json'
if (-not (Test-Path -LiteralPath $configPath)) { throw 'node-config.json is missing.' }
$config = Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
if (-not $config.finalized) { throw 'This package is not finalized and cannot be installed.' }

$besuSource = Join-Path $RuntimeSource 'besu-26.6.1'
$jdkSource = Join-Path $RuntimeSource 'jdk-25.0.3+9'
if (-not (Test-Path -LiteralPath (Join-Path $besuSource 'lib'))) { throw 'Besu runtime is missing.' }
if (-not (Test-Path -LiteralPath (Join-Path $jdkSource 'bin\java.exe'))) { throw 'JDK runtime is missing.' }

New-Item -ItemType Directory -Force -Path $InstallRoot | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $InstallRoot 'runtime') | Out-Null
Copy-Item -LiteralPath $besuSource -Destination (Join-Path $InstallRoot 'runtime\besu') -Recurse -Force
Copy-Item -LiteralPath $jdkSource -Destination (Join-Path $InstallRoot 'runtime\jdk') -Recurse -Force

foreach ($file in @('node-config.json', 'genesis.json', 'static-nodes.json', 'key', 'key.pub', 'start-validator.ps1')) {
  Copy-Item -LiteralPath (Join-Path $PackageDir $file) -Destination (Join-Path $InstallRoot $file) -Force
}

$acl = Get-Acl -LiteralPath (Join-Path $InstallRoot 'key')
$acl.SetAccessRuleProtection($true, $false)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($env:USERNAME, 'FullControl', 'Allow')
$acl.SetAccessRule($rule)
Set-Acl -LiteralPath (Join-Path $InstallRoot 'key') -AclObject $acl

$startup = [Environment]::GetFolderPath('Startup')
$launcher = Join-Path $startup 'PLAIS Validator.cmd'
$line = "@powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$InstallRoot\start-validator.ps1`""
[IO.File]::WriteAllText($launcher, $line + [Environment]::NewLine, (New-Object Text.UTF8Encoding($false)))

Start-Process powershell -WindowStyle Hidden -ArgumentList @(
  '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $InstallRoot 'start-validator.ps1')
)
Write-Host "PLAIS validator installed: $($config.pcName)" -ForegroundColor Green
Write-Host "Install root: $InstallRoot"
