#!/bin/bash

set -eu
PHP=/cygdrive/c/bin/php/php.exe
THREADS=4

buildsite() {

	local basedir="$(realpath .)"
	local rebuild="${basedir}/rebuild.php"	
	
	if [[ "$(uname -o)" == "Cygwin" ]] ; then
		rebuild="$(cygpath -w "$rebuild")"
	fi

	echo "Site: ${1}"

	pushd "$1" >/dev/null

	echo "Cleaning target directory..."

	if [[ -d wwwroot ]] ; then
		rm -r wwwroot
	fi
	
	mkdir -p wwwroot/srv
	
	if [[ ! -d static ]] ; then
		mkdir static
	fi
	cp "${basedir}/static_global/"* wwwroot || true
	cp static/* wwwroot || true
	
	for htm in footer header homepage_blurb ; do
		if [[ ! -f "${htm}.htm" ]] ; then
			touch "${htm}.htm"
		fi
	done

	echo "Building pages..."

	for i in $(seq 0 "$THREADS") ; do
		$PHP "$rebuild" "$THREADS" "$i" &
	done
	wait

	echo "Site: ${1} finished."
	echo ""
		
	popd >/dev/null
}

main() {
	for site in sites/* ; do
		buildsite "$site"
	done
}

main "$@"

read -p "Press any key to continue..."
