$ErrorActionPreference = 'Stop';

function Register-Deployment {
	[CmdletBinding()]
	param(
		[Parameter(Mandatory = $true)]
		$deploymentDetails
	)

	try {
		$newRelicConfig = Read-NewRelicConfiguration
		
		if (-not $newRelicConfig) {
			Write-Warning 'No NewRelic configuration (API key, application name); deployment will not be marked.'
			return;
		}
		
		$userName = "$($env:USERDOMAIN)\$($env:USERNAME)";
		$description = "$($deploymentDetails.jiraReference) ($env:COMPUTERNAME): $($deploymentDetails.Description)";
		
		if ($userName.Length -gt 31) {
			$userName = $userName.Substring(0, 31); # this is the NewRelic limit
		}
		
		$webClient = New-Object 'System.Net.WebClient';
		$webClient.Headers['x-api-key'] = $newRelicConfig.apiKey;
		
		$details = New-Object 'System.Collections.Specialized.NameValueCollection';
		$details['deployment[app_name]'] = $newRelicConfig.appName;
		$details['deployment[user]'] = $userName;
		$details['deployment[description]'] = $description;
		
		Write-Host "Registering deployment for app $($newRelicConfig.appName)";
	
		$respArray = $webClient.UploadValues(
			'https://api.newrelic.com/deployments.xml',
			$details);
			
		$response = [System.Text.Encoding]::Utf8.GetString($respArray);
		Write-Debug $response
		
		Write-Host -Message 'Successfully marked deployment in NewRelic'
	} catch {
		Write-Warning -Message "Could not mark the deployment in NewRelic. This does not affect the application of the hotfix. Failure details: $_";
	}
}

function Read-NewRelicConfiguration {
	$basePath = 'C:\ProgramData\New Relic';
	$apiKeyFilePath = (Join-Path $basePath 'apikey.txt');
	$configFilePath = (Join-Path $basePath '.NET Agent\newrelic.config');
	
	if (-not (Test-Path $apiKeyFilePath) -or -not (Test-Path $configFilePath)) {
		return $null;
	}
	
	$config = @{
		apiKey = '';
		appName = '';	
	};
	
	$config.apiKey = (Get-Content $apiKeyFilePath | select -First 1);
	$config.appName = ([xml](Get-Content $configFilePath)).configuration.application.name;
	
	if (-not $config.apiKey -or -not $config.appName) {
		return $null
	}
	
	return $config;
}
