
Write-Host "Install xampp"

$XAMPP_INSTALLER = "xampp-win32-7.3.1-0-VC15-installer.exe"
$XAMPP_DIR = "c:\xampp"
$XAMPP_VERSION = "$XAMPP_DIR\posapp_version.txt"

$SRC = split-path -parent $MyInvocation.MyCommand.Definition
$XAMPP_SRC_DIR="$($SRC)\xampp"

if (!(Test-Path $XAMPP_SRC_DIR)) {
	Write-Error "Missing directory $XAMPP_DIR"
	return 1
}

if (!(Test-Path $XAMPP_DIR) -or !(Test-Path $XAMPP_VERSION) -or !(Select-String -Path $XAMPP_VERSION -Pattern $XAMPP_INSTALLER -SimpleMatch)) {
	$install_xampp = 1
	Write-Warning "XAMPP must be installed"
} else {
	$install_xampp = 0
	Write-Warning "XAMPP already installed"
}

if ($install_xampp) {
	$XAMPP_INSTALL="$XAMPP_SRC_DIR\$XAMPP_INSTALLER"
	if (!(Test-Path $XAMPP_INSTALL)) {
	  $url = "https://download.byemisys.com/posapp/$XAMPP_INSTALLER"
	  Write-Warning "Downloading xampp install file from $url"
	  $client = new-object System.Net.WebClient
	  $client.DownloadFile($url, $XAMPP_INSTALL)
	}

	Write-Output "Allow Apache through firewall"
	Remove-NetFirewallRule -DisplayName "Apache HTTP Server" -ErrorAction Ignore
	New-NetFirewallRule -DisplayName "Apache HTTP Server" -Direction Inbound -Program "$XAMPP_DIR\apache\bin\httpd.exe" -Action Allow
	New-NetFirewallRule -DisplayName "Apache HTTP Server" -Direction Outbound -Program "$XAMPP_DIR\apache\bin\httpd.exe" -Action Allow

	Write-Output "Installing XAMPP..."
	cmd /c "`"$XAMPP_INSTALL`" --optionfile `"$XAMPP_SRC_DIR\install-xampp-options.txt`""

	Copy-Item "$XAMPP_SRC_DIR\httpd.conf" -Destination "$XAMPP_DIR\apache\conf"

	Write-Output "Installing MySQL as an Service"
	cmd /c  "`"$XAMPP_DIR\mysql\bin\mysqld`" --install mysql --defaults-file=`"$XAMPP_DIR\mysql\bin\my.ini`""
	Write-Output "Try to start the MySQL daemon as service ..."
	Start-Service MySQL

	Write-Output "Installing Apache as an Service"
	cmd /c "`"$XAMPP_DIR\apache\bin\httpd`" -k install"
	Write-Output "Try to start Apade daemon as a service ..."
	Start-Service Apache2.4

	$XAMPP_INSTALLER > $XAMPP_VERSION
}

Copy-Item "$XAMPP_SRC_DIR\httpd.conf" -Destination "$XAMPP_DIR\apache\conf"
Copy-Item "$XAMPP_SRC_DIR\htpasswd" -Destination $XAMPP_DIR
Copy-Item "$XAMPP_SRC_DIR\htaccess.txt" -Destination "$XAMPP_DIR\htdocs\.htaccess"
Copy-Item "$XAMPP_SRC_DIR\httpd-xampp.conf" -Destination "$XAMPP_DIR\apache\conf\extra"
