param(
	[parameter(ValueFromRemainingArguments=$true)]
	$pesterArgs
)

$ErrorActionPreference = 'Stop';

function Find-PesterInstallation {
	$pesterCommand = $null;

	# try to find it in the path
	$pesterCommand = (Get-Command 'pester.bat*' | Select-Object -First 1 -ExpandProperty 'Definition');

	if (-not $pesterCommand) {
		# try to find it in the modules path
		$pesterModulesPath = Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsPowerShell\Modules\Pester'
		$pesterCommand = (Get-ChildItem $pesterModulesPath -Include 'pester.bat' -Recurse -ErrorAction 'SilentlyContinue' | Sort-Object 'LastWriteTime' -Descending | Select-Object -First 1 -ExpandProperty 'FullName');
	}

	return $pesterCommand;
}

$pesterBatPath = Find-PesterInstallation

if (-not $pesterBatPath) {
	# Install Chocolatey if necessary
	if (@(get-command 'choco*.exe*').Count -eq 0) {
		(New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1') | Invoke-Expression
	}

	# Install Pester via Chocolatey
	choco install pester --force --yes
}

$pesterBatPath = Find-PesterInstallation

if (-not $pesterBatPath) {
	throw 'Could not discover Pester installation'
}

Write-Host "Running Pester from $pesterBatPath"

# Invoke Pester to find all test files, inspect for test methods and execute them all
& $pesterBatPath @pesterArgs
