param (
    [Switch]$StopIIS
)

&"$PSScriptRoot/../Scripts/vars.ps1"

trap {
	iisreset /start
	throw $_
}

$phpVersion = $PHP_VERSION_FULL
if ($args.count -eq 1) 
{
	$phpVersion = $args[0]
}

if (-Not($phpVersion -match "^" + $PHP_VERSION))
{
	Write-Host "PHP Version not in correct Major Version: $PHP_VERSION"
	exit
}

$zipFile = "$ROOT/Var/Upgrade/php.zip"
$zipFolder = "$ROOT/Var/Upgrade/php"

if (Test-Path $zipFile -PathType Leaf)
{
	try {[void](Expand-Archive -Force $zipFile -DestinationPath $zipFolder)}
	catch {	Remove-Item $zipFile -Force}
} 

if (-Not(Test-Path $zipFile -PathType Leaf)) 
{
	Write-Host "Begin download for PHP $phpVersion"
	$primaryUrl = "https://windows.php.net/downloads/releases/php-$phpVersion-nts-Win32-vs16-x64.zip"
	$backupUrl = "https://windows.php.net/downloads/releases/archives/php-$phpVersion-nts-Win32-vs16-x64.zip"

	try { Invoke-WebRequest -Uri $primaryUrl -OutFile $zipFile -SkipCertificateCheck }
	catch {
		if ($_.Exception.Response.StatusCode -eq 404) {
			Invoke-WebRequest -Uri $backupUrl -OutFile $zipFile -SkipCertificateCheck
		} else {
			throw $_
		}
	}
}

Expand-Archive -Force $zipFile -DestinationPath $zipFolder

if ($StopIIS) {
	iisreset.exe /stop
	Stop-Process -Name php-cgi, php -Force -ErrorAction SilentlyContinue
}

[void](New-Item -Path $PHPdir -ItemType Directory -ErrorAction Continue -Force)
Copy-Item -Force -Recurse "$zipFolder/*" "$PHPdir"

$Global:PhpVOutput = &"$PHPexe" -v

if ($PhpVOutput -match ".*" + "$phpVersion" + ".*")
{
	Remove-Item $zipFile -Force
	Remove-Item "$zipFolder" -Recurse -Force

    $oldpath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path
    # TODO if change in version
    $oldpath = $oldpath -replace "C:\\Program Files\\PHP\\v5\.6\\?","" 
    $oldpath = $oldpath -replace "C:\\Program Files\\PHP\\v7\.1\\?","" 
    $oldpath = $oldpath -replace "C:\\Program Files\\PHP\\v7\.2\\?","" 
    $oldpath = $oldpath -replace "C:\\Program Files\\PHP\\v7\.4\\?","" 
    $oldpath = $oldpath -replace "C:\\Program Files\\PHP\\v8\.0\\?",""
	$oldpath = $oldpath -replace "C:\\Program Files\\PHP\\v8\.3\\?",""
    $phpPath = "C:\Program Files\PHP\v$PHP_VERSION\";
    $newpath = "$oldpath;$phpPath"
    Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newpath
	
	Write-Host "Upgrade complete."
}
 else 
{
	Write-Host "PHP Upgrade failed"
	Write-Host $PHPdir
	Write-Host $phpVersion
	Write-Host $PhpVOutput
}

iisreset /start