$ErrorActionPreference = 'Stop'

$Source = Split-Path -Parent $MyInvocation.MyCommand.Path
$Target = Join-Path $env:LOCALAPPDATA 'EdgeEngineAgent'

Write-Host 'Installing Edge Engine Agent...' -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path $Target | Out-Null

Get-ChildItem -Path $Source -Force | Where-Object { $_.Name -ne 'Install-Edge-Agent.ps1' } | ForEach-Object {
  Copy-Item $_.FullName -Destination $Target -Recurse -Force
}
Copy-Item $MyInvocation.MyCommand.Path -Destination (Join-Path $Target 'Install-Edge-Agent.ps1') -Force

$ProtocolRoot = 'HKCU:\Software\Classes\edgeengine'
New-Item -Path $ProtocolRoot -Force | Out-Null
Set-ItemProperty -Path $ProtocolRoot -Name '(default)' -Value 'URL:Edge Engine Agent'
Set-ItemProperty -Path $ProtocolRoot -Name 'URL Protocol' -Value ''
New-Item -Path "$ProtocolRoot\DefaultIcon" -Force | Out-Null
Set-ItemProperty -Path "$ProtocolRoot\DefaultIcon" -Name '(default)' -Value (Join-Path $Target 'node.exe')
New-Item -Path "$ProtocolRoot\shell\open\command" -Force | Out-Null
$Launch = Join-Path $Target 'launch-protocol.ps1'
$Command = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "' + $Launch + '" "%1"'
Set-ItemProperty -Path "$ProtocolRoot\shell\open\command" -Name '(default)' -Value $Command

$Shell = New-Object -ComObject WScript.Shell
$Desktop = [Environment]::GetFolderPath('Desktop')
$Shortcut = $Shell.CreateShortcut((Join-Path $Desktop 'Edge Engine Agent.lnk'))
$Shortcut.TargetPath = (Join-Path $Target 'Start-Edge-Agent.cmd')
$Shortcut.WorkingDirectory = $Target
$Shortcut.Description = 'Start the Edge Engine local trading agent'
$Shortcut.Save()

$SetupShortcut = $Shell.CreateShortcut((Join-Path $Desktop 'Edge Engine Setup.lnk'))
$SetupShortcut.TargetPath = (Join-Path $Target 'Setup-Edge-Agent.cmd')
$SetupShortcut.WorkingDirectory = $Target
$SetupShortcut.Description = 'Open secure local ProjectX setup'
$SetupShortcut.Save()

Write-Host ''
Write-Host 'Edge Engine Agent installed.' -ForegroundColor Green
Write-Host "Location: $Target"
Write-Host 'Return to Edge Engine > Connections and click Connect Topstep.'
Write-Host 'Do not enter ProjectX credentials until Connect Topstep launches the paired setup session.'
