# Set up constants.
$inno = 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe'
$version = '%VERSION%'

# Any error kills the script.
$ErrorActionPreference = 'Stop'

# Set up Azure login to do signing.
Connect-AzAccount -TenantId 16375de7-ceed-4050-a848-5002e9b8f912 -SubscriptionName Pay-As-You-Go

# Sign the binaries that have not been signed yet.
$files = (Get-ChildItem -Path obj -Recurse -Filter "*.exe").FullName |
    Where-Object { (Get-AuthenticodeSignature $_).Status -eq "NotSigned" }
if ($files.Count -ne 0)
{
    Write-Host -ForegroundColor Green 'Signing', $files.Count, 'binaries'
    & .\run-signtool.ps1 $files
}

# Create the noinstall files.
Write-Host -ForegroundColor Green 'Creating no-install zipfiles'
if (Test-Path wc3270-$version-noinstall-32.zip) {
    Remove-Item wc3270-$version-noinstall-32.zip
}
$zip32 = Get-Content .\wc3270\wc3270-32.zipit
Compress-Archive -Path $zip32 -DestinationPath wc3270-$version-noinstall-32.zip
if (Test-Path wc3270-$version-noinstall-64.zip) {
    Remove-Item wc3270-$version-noinstall-64.zip
}
$zip64 = Get-Content .\wc3270\wc3270-64.zipit
Compress-Archive -Path $zip64 -DestinationPath wc3270-$version-noinstall-64.zip

# Create the wx3270 extern zipfiles.
Write-Host -ForegroundColor Green 'Creating wx3270 extern zipfiles'
if (Test-Path wx3270-$version-extern-32.zip) {
    Remove-Item wx3270-$version-extern-32.zip
}
$zip32 = Get-Content .\wc3270\wx3270-32.zipit
Compress-Archive -Path $zip32 -DestinationPath wx3270-$version-extern-32.zip
if (Test-Path wx3270-$version-extern-64.zip) {
    Remove-Item wx3270-$version-extern-64.zip
}
$zip64 = Get-Content .\wc3270\wx3270-64.zipit
Compress-Archive -Path $zip64 -DestinationPath wx3270-$version-extern-64.zip

# Run Inno Setup to create the installer.
Write-Host -ForegroundColor Green 'Running Inno Setup'
# The signtool command passed to Inno Setup is a bit strange, but passing the current directory through an
# environment variable overcomes the problem of Inno Setup running from its own install directory, and the
# peculiarities of trying to pass the pathname of the run-signtool script (which may contain spaces) through
# various layers of Inno Setup and PowerShell.
$Env:mydir = (Get-Location)
$signparm = '/smystandard="powershell.exe -command $q& { & $$Env:mydir\run-signtool.ps1 ''$f'' }$q"'
& $inno $signparm /Qp wc3270.iss

# Archive to bgp.nu and moby.
Write-Host -ForegroundColor Green 'Archiving to bgp.nu'
$v=[int[]]($version -split "\." -replace "[a-z].*", "")
$vdir="{0:D2}.{1:D2}" -f @($v)
& scp wc3270-$version-setup.exe wc3270-$version-noinstall-32.zip wc3270-$version-noinstall-64.zip bgp.nu:www/download/$vdir/
Write-Host -ForegroundColor Green 'Archiving to moby'
& scp wc3270-$version-setup.exe wc3270-$version-noinstall-32.zip wc3270-$version-noinstall-64.zip 10.0.0.12:gr/
