$ErrorActionPreference = "Stop"

$root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$shell = New-Object -ComObject WScript.Shell

$candidates = New-Object System.Collections.Generic.List[string]

foreach ($path in @(
  [Environment]::GetFolderPath([Environment+SpecialFolder]::DesktopDirectory),
  [Environment]::GetFolderPath("Desktop"),
  $shell.SpecialFolders.Item("Desktop")
)) {
  if ($path -and -not $candidates.Contains($path)) {
    $candidates.Add($path)
  }
}

if ($env:OneDrive) {
  $path = Join-Path $env:OneDrive "Desktop"
  if (-not $candidates.Contains($path)) {
    $candidates.Add($path)
  }
}

if ($env:USERPROFILE) {
  $path = Join-Path $env:USERPROFILE "Desktop"
  if (-not $candidates.Contains($path)) {
    $candidates.Add($path)
  }
}

$desktop = $candidates | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
if (-not $desktop) {
  $desktop = Join-Path $env:USERPROFILE "Desktop"
  New-Item -ItemType Directory -Force -Path $desktop | Out-Null
}

$shortcutPath = Join-Path $desktop "Liberty Raceworks Pro.lnk"
$shortcut = $shell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = Join-Path $root "Start Liberty Raceworks Pro.bat"
$shortcut.WorkingDirectory = $root
$iconPath = Join-Path $root "Liberty Raceworks Pro Sharp.ico"
if (-not (Test-Path -LiteralPath $iconPath)) {
  $iconPath = Join-Path $root "Liberty Raceworks Pro.ico"
}
$shortcut.IconLocation = $iconPath + ",0"
$shortcut.Description = "Launch Liberty Raceworks Pro"
$shortcut.WindowStyle = 1
$shortcut.Save()

Write-Host "Created shortcut:"
Write-Host $shortcutPath
