#Requires -Version 3.0
if (Test-Path Env:\DEBUG) {
  Set-PSDebug -Trace 1
}
$Host.UI.RawUI.WindowTitle = "WizardKit: Winget wrapper"
$Host.UI.RawUI.BackgroundColor = "black"
$Host.UI.RawUI.ForegroundColor = "white"


## Functions ##
function Abort {
  Write-Host -ForegroundColor "Red" "`nAborted."
  WKPause "Press Enter to exit..."
  exit
}
function WKPause ($Message = "Press Enter to continue... ") {
  Write-Host $Message -NoNewLine
  Read-Host
}

## PowerShell equivalent of Python's "if __name__ == '__main__'"
# Code based on StackOverflow comments
# Question:     https://stackoverflow.com/q/4693947
# Using answer: https://stackoverflow.com/a/5582692
# Asked by:     https://stackoverflow.com/users/65164/mark-mascolino
# Answer by:    https://stackoverflow.com/users/696808/bacon-bits
if ($MyInvocation.InvocationName -ne ".") {
  Clear-Host

  # Check for winget and install if missing
  Write-Host "WizardKit: winget wrapper`n`n`n`n`nInitializing..."
  try {
    $_ = $(winget --version)
  }
  catch {
    Write-Host ("  ERROR: Failed to run winget." ) -ForegroundColor "Red"
    Write-Host "  Installing winget..."
    Add-AppxPackage -RegisterByFamilyName -MainPackage Microsoft.DesktopAppInstaller_8wekyb3d8bbwe
  }
  try {
    $_ = $(winget --version)
  }
  catch {
    Write-Host ("  ERROR: Failed to run or install winget." ) -ForegroundColor "Red"
    Abort
  }

  # List available upgrades
  Start-Process -FilePath "winget" -ArgumentList @("upgrade") -NoNewWindow -Wait
  WKPause "`nPress Enter to install listed applications... "

  # Install upgrades
  Start-Process -FilePath "winget" -ArgumentList @("upgrade", "--all") -NoNewWindow -Wait
}
