$ErrorActionPreference = 'Stop'

$PackageRoot = Split-Path -Parent $PSScriptRoot
$InstallRoot = Join-Path $env:LOCALAPPDATA 'ORCLocal'
$TaskName = 'ORC Local Worker'

Write-Host "Installing ORC Local to $InstallRoot"
New-Item -ItemType Directory -Force -Path $InstallRoot | Out-Null

$Items = @('app', 'backend', 'scripts', 'tools', 'README.md')
foreach ($Item in $Items) {
  $Source = Join-Path $PackageRoot $Item
  if (!(Test-Path $Source)) {
    continue
  }
  $Destination = Join-Path $InstallRoot $Item
  if (Test-Path $Destination) {
    Remove-Item -LiteralPath $Destination -Recurse -Force
  }
  Copy-Item -LiteralPath $Source -Destination $Destination -Recurse -Force
}

Push-Location $InstallRoot
try {
  powershell -ExecutionPolicy Bypass -File .\scripts\setup.ps1
  powershell -ExecutionPolicy Bypass -File .\scripts\install_tesseract_windows.ps1

  $RunScript = Join-Path $InstallRoot 'scripts\run_worker.ps1'
  $Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$RunScript`""
  $Trigger = New-ScheduledTaskTrigger -AtLogOn
  $Principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive
  Register-ScheduledTask -TaskName $TaskName -Action $Action -Trigger $Trigger -Principal $Principal -Description 'Runs ORC Local OCR worker for orc.thanganhai.com.' -Force | Out-Null
  Start-ScheduledTask -TaskName $TaskName
  Start-Process 'http://127.0.0.1:8765/'
}
finally {
  Pop-Location
}

Write-Host 'ORC Local installed. It will start automatically when you sign in.'
