#!/usr/bin/env bash

unitTestsDirectory=$(dirname "$(readlink --canonicalize-existing "${BASH_SOURCE[0]}")")
vendorDirectory="${unitTestsDirectory}/vendor";
phpUnitPath="${vendorDirectory}/bin/phpunit"

function runUnitTests() {
	if ! which composer > /dev/null
	then
		if ! installComposer
		then
			error 'Composer is not installed. Please follow the installation instructions here: https://getcomposer.org/download/'
			exit 1
		fi
	fi

	if [ ! -d "$vendorDirectory" ]
	then
		composer update
	fi

	local currentDirectory="$PWD"

	cd "${unitTestsDirectory}"

	# Run the unit tests
	"${phpUnitPath}"

	cd "${currentDirectory}"
}

function installComposer() {
	local installerUrl='https://getcomposer.org/installer'
	local installerPath='/tmp/install-composer.php'
	local composerDirectory='/usr/local/bin'
	local composerFilename='composer'

	if ! php -r "exit((int)!@copy('$installerUrl', '$installerPath'));"
	then
		return 1
	fi

	echo "Installing Composer to '${composerDirectory}/${composerFilename}'..."
	sudo php "$installerPath" --install-dir="$composerDirectory" --filename="$composerFilename"
	status="$?"

	rm -f "$installerPath"
	return "$status"
}

function error() {
	echo "$@" 1>&2
}

runUnitTests
