# -----------------------------------------------------------------------------
#                    S C R I P T   S P E C I F I C A T I O N
#                    Copyright 2019 Motorola Solutions, Inc.
#                              All Rights Reserved.
#                   Motorola Solutions Confidential Restricted
# -----------------------------------------------------------------------------

<#
.SYNOPSIS
    Name: RunScriptFromRegistry.ps1 run just one script from registry for test purposes
.DESCRIPTION
    Script will run one script that is provided through the given registry path
    HKLM:\SOFTWARE\Motorola\MotoPatch[ProductName]\[InstalationPhase]Scripts\[] (ex: HKLM:\SOFTWARE\Motorola\MotoPatchOpenJDK\PostInstallConfigScripts\fixSomething)
    Example of registry structure:
    HKLM:\SOFTWARE\Motorola\MotoPatchOpenJDK
    |
    *---PreInstallConfig
        |
        *---*--------------------------------------------------------------------------------------------*
            *      Name      |                                    Data                                   *
            *--------------------------------------------------------------------------------------------*
            * 2.FixSomething | powershell.exe C:\fixsomething.ps1 -argument1 -argument2 valueForArgument *
            *--------------------------------------------------------------------------------------------*
            * 1.MyBatScript  | C:\anotherSc.bat                                                          *
            *--------------------------------------------------------------------------------------------*
.EXAMPLE
    Be sure that you are providing correct registry path
    RunScriptFromRegistry.ps1 -RegistryKeyPath "HKLM:\SOFTWARE\Motorola\MotoPatchOpenJDK\PostInstallConfigScripts\KeyValue"
#>

# MODIFICATION HISTORY
# Date         Change
# -----------------------------------------------------------------------------
# 18 Dec 19    Initial creation
# -----------------------------------------------------------------------------
[CmdletBinding(SupportsShouldProcess = $true)]
param (
    #Path to registry key which contains script path
    [Parameter(Mandatory = $true)] [String] $RegistryKeyPath,
    #Name of the product for which you want run a custom scripts
    [Parameter(Mandatory = $false)] [String]$LogFile
)

Set-Variable -name "SUCCESS" -Value 0 -Option ReadOnly -Force
Set-Variable -name "FAILURE" -Value 1 -Option ReadOnly -Force

$scriptPath = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
$scriptName = $MyInvocation.MyCommand.Name #variable important for write-log function

. "$scriptPath\scripts\LoggingFunctions.ps1"

$registryProperty = Split-Path -Path $RegistryKeyPath -Leaf
$registrySubKey = Split-Path -Path $RegistryKeyPath -Parent

$returnValue = $SUCCESS
$stdOutFile = "C:\Windows\debug\stdOutputFile_$($registryProperty).txt"
$stdErrFile = "C:\Windows\debug\stdErrorFile_$($registryProperty).txt"

if ( -not (Test-Path $registrySubKey)) {
    Write-Log "Given registry path $RegistryKeyPath doesn't exist" -type $ERROR_C
    exit $FAILURE
}

if ( [String]::IsNullOrWhiteSpace($LogFile) ) {
    $LogFile = "C:\Windows\Debug\RunScriptFromRegistry_$($registryProperty).log"
}
Write-Log "Logfile path: $LogFile"

try {
    $currentScriptNameWithPathAndArguments = (Get-Item $RegistrySubKey).GetValue("$registryProperty")
}
catch {
    Write-Log "$_"
    exit $FAILURE
}

if ( [String]::IsNullOrWhiteSpace($currentScriptNameWithPathAndArguments)) {
    Write-Log "There is no such value called '$registryProperty' or is empty!" -type $ERROR_C
    exit $FAILURE
}

Write-Log "Trying to run $currentScriptNameWithPathAndArguments"
Write-Log "Report of running custom script $($currentScriptNameWithPathAndArguments)"
Write-Log "============================================================================================"

try {
    $currentScriptProc = Start-Process cmd.exe -ArgumentList "/C $currentScriptNameWithPathAndArguments" -Wait -PassThru -RedirectStandardError $stdErrFile -RedirectStandardOutput $stdOutFile
}
catch {
    Write-Log "$($_.Exception.Message)" -type $ERROR_C
    exit $FAILURE
}

if ( (Get-Item $stdOutFile).Length -gt 0 ) {
    Write-Log "$(Get-Content $stdOutFile)"
}

if ( (Get-Item $stdErrFile).Length -gt 0 ) {
    Write-Log "There was an error during execution of custom script $($currentScriptNameWithPathAndArguments)."
    Write-Log "$(Get-Content $stdErrFile)" -type $ERROR_C
}

if ( $currentScriptProc.ExitCode -ne 0) {
    Write-Log "$_ returned $($currentScriptProc.ExitCode) exit code." -type $ERROR_C
    $returnValue = $currentScriptProc.ExitCode
}

Write-Log "Exit code: $returnValue"
Write-Log "============================================================================================"
Write-Log "End of script output"

Remove-Item $stdOutFile
Remove-Item $stdErrFile
exit $returnValue