#Run with       powershell -ExecutionPolicy Bypass -File .\updater.ps1

$ProgressPreference = "SilentlyContinue"
$latestUrl = "https://jsedano.duckdns.org/ballenaWinUpdate/latest.txt"
Write-Output "Downloading $latestUrl"
$latestWebContent = Invoke-WebRequest -UseBasicParsing -Uri $latestUrl -TimeoutSec 60
if ($latestWebContent -eq $null) {
  Write-Output "Unable to download $latestUrl"
  exit 1
}
$latest = $latestWebContent.Content.Trim()
Write-Output "Latest available version: $latest"
$current = [IO.File]::ReadAllText(".\current.txt").Trim()
Write-Output "Current installed version: $current"
if ($current -eq $latest) {
	Write-Output "Already updated, skipping"
	exit 0
}
Write-Output "Out of date, installing"
$jarUrl = "https://jsedano.duckdns.org/ballenaWinUpdate/ballena-$latest.jar"
Write-Output "Downloading $jarUrl"
$newJarWebContent = Invoke-WebRequest -UseBasicParsing -Uri $jarUrl -OutFile ".\ballena.jar.new" -PassThru -TimeoutSec 120
if ($newJarWebContent -eq $null) {
	Write-Output "Unable to download $jarUrl"
	exit 1
}
Write-Output "Downloaded $jarUrl"
& ".\ballenaServiceWrapper" stop
do {
	Start-Sleep -Seconds 1
	$status = .\ballenaServiceWrapper status
	Write-Output "Service: $status"
} while ($status -ne "Stopped")

& del ballena.jar
& ren ballena.jar.new ballena.jar
& ".\ballenaServiceWrapper" start
Write-Output "Setting current version to $latest"
$latest > current.txt
#Set-Content -Path ".\current.txt" -Value "$latest"
Write-Output "Finished"
