param(
	[switch]
	$Revert
)

$ErrorActionPreference = 'Stop';

[bool]$doInstall = -not $Revert;

# include the common modules
$scriptDir = (Split-Path $script:MyInvocation.MyCommand.Path);
$modulesDir = Join-Path $scriptDir 'scripts\modules\'
$modules = @(
	'Hash.psm1', 
	'FileSets.psm1', 
	'FnmsEnvironment.psm1', 
	'FnmsServices.psm1', 
	'NewRelic.psm1', 
	'ScheduledTasks.psm1'
) | ForEach-Object { Join-Path $modulesDir $_ }

Import-Module -Force -Name $modules

if (-not (Test-ProcessElevated)) {
	throw 'Hotfix application requires elevation: please ensure you run with the "Run as administrator" rights.'
}

# find the FNMS installation folder 
# (also available: Get-ImportXMLDirectory, Get-LoggingConfigurationDirectory)
$productInstallDirectoryPath = Get-InstallationDirectory;

# Ensure that this patch is running on a server with the required components
# This isn't required for multi-server patches 
# See the definition of Assert-InstalledComponent in common.ps1 for possible component names
Assert-InstalledComponent 'BatchServer';

Set-MaxScreenWidth;

#
# Set up the sets of files to copy: the first is a sub-folder from the hotfix
# under 'files', and the second argument is the destination folder root in the
# installation. There may be multiple file sets.
#
# If an XML transform is required, commit the XDT transform with a filename that mirrors the file
# to be transformed, and adds an '.xdt' extension. For example, to change the web.config, place
# a web.config.xdt file in the source folder. If you need to turn this off, supply -Transform:$false
# to the New-FileSet function.
#
# For installations that vary by the installed components, use Test-InstalledComponent to conditionally
# add filesets to the $fs array. Using Test-InstalledVersion allows for adding filesets based on the
# installed server version. So you can vary for Batch/Presentation/Inventory servers, as well as
# have the correct payload for different major/service pack versions.
# 

$fs = @(
	(New-FileSet '/DotNet/bin' (Join-Path $productInstallDirectoryPath '/DotNet/bin'))
)

$action = @{ Name = 'Installing'; Past = 'Installed' }
if (-not $doInstall) {
	$action = @{ Name = 'Reverting'; Past = 'Reverted' }
}

# apply the hotfix
Write-Host
Write-Host "$($action.Name) patch for $($deploymentDetails.jiraReference)"
Write-Host '================================='
Write-Host


if (-not ($fs | Test-FileSetHasSources)) {
	Write-Error -Message 'No files to install.'
}
else {
	Write-Host 'Hot-fix files to be written'
	Write-Host '---------------------------'
	$fs | ForEach-Object { $_.FileDetails } | Select-Object Source,Dest,Transform | Format-Table -Wrap
}


# add pre-backup logic here

if ($doInstall) {
	Write-Host "Backing up file(s) that are about to be overwritten...";
	$fs | Backup-FileSet -Verbose
}

Write-Host "$($action.Name) hotfix file(s) ...";

# Get states list for all services that needs to in stopped status for the hotfix deployment to succeed.
$serviceNames = @()
#$serviceNames = @('BatchProcessor') # use this if this hotfix is to be deployed to batch server and only batch processor service is involved
#$serviceNames = @('BatchProcessScheduler') # OR use this if this hotfix is to be deployed to batch server and only batch process scheduler service is involved
#$serviceNames = @('BatchProcessor', 'BatchProcessScheduler') # OR use this if this hotfix is to be deployed to batch server and involves both batch processor service and batch process scheduler service

$serviceStates = @($serviceNames | Get-BatchServiceState)

try {
	$serviceStates | Enter-DeploymentMode | Out-Null

	# add pre-copy logic here (if required)

	if ($doInstall) {
		$fs | Copy-FileSet -Verbose
	} else {
		$fs | Restore-FileSet
	}

	# add post-copy logic here (if required)

} finally {
	$serviceStates | Exit-DeploymentMode | Out-Null
}


Write-Host
Write-Host '===============================================================' -ForegroundColor Green
Write-Host
Write-Host "All files $($action.Past.ToLower()) successfully. The deployment is complete." -ForegroundColor Green
Write-Host
Write-Host '===============================================================' -ForegroundColor Green
Write-Host


