param(
  [string]$InstallRoot = (Join-Path $env:LOCALAPPDATA 'PLAIS Validator')
)

$ErrorActionPreference = 'Stop'
$configPath = Join-Path $InstallRoot 'node-config.json'
if (-not (Test-Path -LiteralPath $configPath)) {
  throw "Validator config is missing: $configPath"
}

$config = Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
if (-not $config.finalized) {
  throw 'Validator package is not finalized. Configure all five advertisedHost values first.'
}

$java = Join-Path $InstallRoot 'runtime\jdk\bin\java.exe'
$besuRoot = Join-Path $InstallRoot 'runtime\besu'
$classpath = Join-Path $besuRoot 'lib\*'
$dataPath = Join-Path $InstallRoot 'data'
$genesis = Join-Path $InstallRoot 'genesis.json'
$staticNodes = Join-Path $InstallRoot 'static-nodes.json'

foreach ($required in @($java, $classpath, $genesis, $staticNodes)) {
  if (-not (Test-Path -LiteralPath $required)) { throw "Required validator file is missing: $required" }
}

New-Item -ItemType Directory -Force -Path $dataPath | Out-Null
Copy-Item -LiteralPath (Join-Path $InstallRoot 'key') -Destination (Join-Path $dataPath 'key') -Force
Copy-Item -LiteralPath (Join-Path $InstallRoot 'key.pub') -Destination (Join-Path $dataPath 'key.pub') -Force

$besuArgs = @(
  '--enable-native-access=ALL-UNNAMED',
  '-Xms128m',
  '-Xmx512m',
  '-cp', $classpath,
  'org.hyperledger.besu.Besu',
  "--data-path=$dataPath",
  "--genesis-file=$genesis",
  '--profile=ENTERPRISE',
  '--sync-mode=FULL',
  '--data-storage-format=BONSAI',
  "--p2p-host=$($config.advertisedHost)",
  '--p2p-interface=0.0.0.0',
  "--p2p-port=$($config.p2pPort)",
  '--discovery-enabled=false',
  '--nat-method=NONE',
  "--static-nodes-file=$staticNodes",
  '--min-gas-price=0',
  '--logging=INFO'
)

$env:JAVA_HOME = Join-Path $InstallRoot 'runtime\jdk'
Set-Location $besuRoot
& $java @besuArgs
exit $LASTEXITCODE
