#Requires -Version 5.1

<#PSScriptInfo
#Requires -RunAsAdministrator

    .VERSION 1.0
    .GUID frdepo13-10b0-481d-a26c-389f4cbaa31z
    .AUTHOR Sage X3 R&D
    .COMPANYNAME Sage
    .COPYRIGHT (c) Copyright SAGE 2006-2025. All Rights Reserved.
    .TAGS MSWindows, Linux
    .LICENSEURI
    .PROJECTURI
    .ICONURI
    .EXTERNALMODULEDEPENDENCIES
    .REQUIREDSCRIPTS beforepacks.ps1
    .EXTERNALSCRIPTDEPENDENCIES Powershell-5.1
    .RELEASENOTES
    .PRIVATEDATA
    .SYNOPSIS
       Prepare Runtime Update
    .DESCRIPTION      
      beforepacks.ps1: PowerShell Script to prepare Runtime Update


     .PARAMETER InstallPath
     -InstallPath [ex: "C:\Sage\SafeX3\EDTV2\EDTSRVFRDEP\srvedit"]

    .EXAMPLE
     Powershell.exe -executionpolicy remotesigned -File  .\beforepacks.ps1 -InstallPath "C:\Sage\SafeX3\EDTSRVTEST"

     .NOTES
    Author: Franck DEPOORTERE
    Date:   Nov 01, 2024
     #>

param( 
    [Parameter(Mandatory = $true)] [string] $InstallPath
)

function Get-Formatted-Date() {
    <#
        .SYNOPSIS
            Date formating for Log trace
        .INPUTS
            None
        .OUTPUTS
            Date in a specific Format, such as  2020_09_28_08_36_59_123
    #>
    return Get-Date -Format yyyy_MM_dd_HH_mm_ss_fff
}

function Show-Usage() {
    Add-To-Log -line "Usage: beforepacks.ps1 -InstallPath c:\\Sage\\XXX"
}


function Add-To-Log {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, Position = 1)] [string] $line,
        [Parameter(Mandatory = $false, Position = 2)] [int] $errorLevel
    )
    # Error
    if (($errorLevel -eq 1) -and -Not ([string]::IsNullOrEmpty($SCRIPT_LOGDAT))) {
        Add-Content -Value "Error" -Path $SCRIPT_LOGDAT 
    } 

    if (($errorLevel -eq 0) -And -Not ([string]::IsNullOrEmpty($SCRIPT_LOGDAT)) ) {
        Add-Content -Value $line -Path $SCRIPT_LOGDAT
    }

    if ($errorLevel -eq 1) {
        Write-Error $line
    } 
    else {
        Write-Host $line
    }
}



function Invoke-CommandProcess {
    <#
    .SYNOPSIS
    Launch a command with Linux Shell binary (/bin/sh)
        
    .PARAMETER command
    Command to execute. Ex: "cp file1.txt file2.txt"
    
    .PARAMETER sudoer
    Execute the command with root user.
    #>

    [CmdletBinding()]

    param(
        [Parameter(Mandatory = $true, HelpMessage = "Command to execute")][string]$command,
        [Parameter(Mandatory = $false)] [string]$hideOccurence,
        [Parameter(Mandatory = $false)] [bool]$sudoer
    )

    $proc = New-Object System.Diagnostics.Process
    $stdout = New-Object System.Text.StringBuilder
    $stderr = New-Object System.Text.StringBuilder
    $stdoutEvent = $null
    $stderrEvent = $null
    [string]$errorMessage = $null

    try {
        $pinfo = New-Object System.Diagnostics.ProcessStartInfo        
        if ($IsLinux) {
            $pinfo.FileName = "/bin/sh"
            if ($sudoer -eq $true) {
                $pinfo.UserName = "root"
            }
            $command = $command.Replace("""", "'")
            $pinfo.Arguments = "-c ""$command"" "
        }
        else {
            $pinfo.FileName = "cmd.exe"
            $command = $command.Replace("'", """")
            $pinfo.Arguments = "/c $command ";
        }
        $pinfo.RedirectStandardError = $true
        $pinfo.RedirectStandardOutput = $true
        $pinfo.UseShellExecute = $false
        $pinfo.WorkingDirectory = $PSScriptRoot 
        $pinfo.CreateNoWindow = $true

        $proc.StartInfo = $pinfo
        # deadlocks due to the synchronous call to ReadToEnd(),
        #https://stackoverflow.com/questions/8761888/capturing-standard-out-and-error-with-start-process
        $stdoutEvent = Register-ObjectEvent $proc -EventName OutputDataReceived -MessageData $stdout -Action {
            $Event.MessageData.AppendLine($Event.SourceEventArgs.Data)
        }
          
        $stderrEvent = Register-ObjectEvent $proc -EventName ErrorDataReceived -MessageData $stderr -Action {
            $Event.MessageData.AppendLine($Event.SourceEventArgs.Data)
        }

        $proc.Start() | Out-Null  #  workaround to avoid $null value
        $proc.BeginOutputReadLine()
        $proc.BeginErrorReadLine()
        Wait-Process -Id $proc.Id -TimeoutSec 7200 # $proc.WaitForExit()

        if ($proc.HasExited) {
            $exitCode = $proc.ExitCode
        }
        else {
            Stop-Process -Force -Id $proc.Id
            $exitCode = -1
        }

        # Be sure to unregister.  You have been warned.
        Unregister-Event $stdoutEvent.Id
        Unregister-Event $stderrEvent.Id        
        $errorMessage = ($stderr.ToString()).Trim()
        $output = ($stdout.ToString()).Trim()
        # Check if the command succeeded
        if (($null -ne $exitCode) -and ($exitCode -eq 0)) {
            if (-Not [string]::IsNullOrEmpty($hideOccurence)) {
                $command = $command.Replace($hideOccurence, "<hidden>")
            }

            Add-To-Log -Message "Command succeeded: $command"  -LogMessageType Debug -WriteToOutput $false
            Add-To-Log -Message "Output: $output" -LogMessageType Debug -WriteToOutput $false
            # Sometimes, the output is located on the $errorMessage  
            Add-To-Log -Message "Message: $errorMessage" -LogMessageType Debug -WriteToOutput $false
        }
        else {
            # Write-Host "Command failed with exit code $($proc.ExitCode)  Command: $command"
            if (-not [string]::IsNullOrEmpty($output)) {
                $errorMessage = "$errorMessage `n $($output)"
            }

            if (-not ([string]::IsNullOrWhiteSpace( $errorMessage) ) ) {
                switch ($ErrorAction) {
                    Stop { 
                        throw $errorMessage
                    }
                    Default {}
                }
            } 
        }
    }
    catch {
        if (-Not [string]::IsNullOrEmpty($hideOccurence)) {
            $command = $command.Replace($hideOccurence, "<hidden>")
        }

        Add-To-Log -Message "Error while running cmd $command Error:$($_.Exception.Message)" -LogMessageType Error -WriteToOutput $true

        if ($null -ne $stdoutEvent) {
            Unregister-Event $stdoutEvent.Id
        }
        if ($null -ne $stderrEvent) {
            Unregister-Event $stderrEvent.Id        
        }
        $errorMessage = ($stderr.ToString()).Trim()
        $output = ($stdout.ToString()).Trim()

        if ((-not [string]::IsNullOrEmpty($errorMessage)) -or (-not [string]::IsNullOrEmpty($output))  ) {
            Add-To-Log -Message "$($output) `n $errorMessage" -LogMessageType Error -WriteToOutput $true
        }
        Add-To-Log -Message $_.ScriptStackTrace  -LogMessageType Error -WriteToOutput $false
        Add-To-Log -Message $_.ErrorDetails -LogMessageType Error -WriteToOutput $false
        
        switch ($ErrorAction) {
            Stop { 
                throw
            }
            Default {}
        }
    }

    return   [pscustomobject]@{
        ExitCode = $exitCode
        stdout   = $stdout.ToString()
        stderr   = $errorMessage
    }
}



function Kill-AdxProcess {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)] [string] $ProcessName,
        [Parameter(Mandatory = $true)] [string] $StartWithPath
    )

    Add-To-Log -line "Check running process(es) '$ProcessName' ..." -errorLevel 0
    
    $p = Get-Process -Name "$ProcessName" -ErrorAction SilentlyContinue    
    if ($null -eq $p) {
        Add-To-Log -line "No running process(es) '$ProcessName' found" -errorLevel 0
        return
    }
    if ($isLinux) {
        $pList = Get-Process -Name "$ProcessName" | Select-Object Name, Id, CommandLine    
    }
    # MS Windows
    else {
        # Check if running PowerShell 7+
        if ($PSVersionTable.PSVersion.Major -ge 7) {
            $pList = Get-Process -Name "$ProcessName" | Select-Object Name, Id, CommandLine    
        } 
        # PowerShell 5.1
        else {
            $ProcessName = "$($ProcessName).exe"        
            $pList = Get-CimInstance Win32_Process -Filter "name = '$ProcessName'" | Select-Object Name, ProcessId, CommandLine    
        }
    }
    if ( $pList.GetType().Name -eq "Object[]") {
        $i = 0
        foreach ($pp in $pList) {
            $processId = $($pp.Id)
            if ( $IsLinux) {
                $processId = $($pp.Id)
            }
            else {
                # Check if running PowerShell 7+
                if ($PSVersionTable.PSVersion.Major -ge 7) {
                    $processId = $($pp.Id)
                } 
                # PowerShell 5.1
                else {
                    $processId = $($pp.ProcessId)
                }
            }
            Add-To-Log -line "$i - Checking process '$ProcessName': $pp" -errorLevel 0
            if ($pp.CommandLine.StartsWith($StartWithPath, [System.StringComparison]::InvariantCultureIgnoreCase)) {
                # Stop-Process -Id 3952
                Add-To-Log -line "$i - Killing process '$ProcessName'  Id=$processId  CommandLine=$($pp.CommandLine)" -errorLevel 0
                Stop-Process -Id $processId -Force
                Add-To-Log -line "$i - process '$ProcessName' Id=$processId killed" -errorLevel 0
                Start-Sleep -Seconds 5
            }
            else {
                Add-To-Log -line "$i - Skip process '$ProcessName'  Id=$processId CommandLine=$($pp.CommandLine)" -errorLevel 0
            }
            $i++    
        }
    }
    elseif ($pList) {
        Add-To-Log -line "Checking process '$ProcessName': $pList" -errorLevel 0
        if ($pList.CommandLine.StartsWith($StartWithPath, [System.StringComparison]::InvariantCultureIgnoreCase)) {
            $processId = $($pList.Id)
            # Check if running PowerShell 7+
            if ($PSVersionTable.PSVersion.Major -ge 7) {
                $processId = $($pList.Id)
            } 
            # PowerShell 5.1
            else {
                $processId = $($pList.ProcessId)
            }

            Add-To-Log -line "Killing process '$ProcessName'  Id=$processId  CommandLine=$($pList.CommandLine)" -errorLevel 0
            Stop-Process -Id $processId -Force
            Start-Sleep -Seconds 5
        }
    }
    else {
        Add-To-Log -line "No running process(es) '$ProcessName' found" -errorLevel 0
    }
} 



<###########################################################
#   MAIN SCRIPT ENTRY POINT                               #
###########################################################>
try {

    $LOGDAT = Get-Formatted-Date
    $SCRIPT_LOG_BASE = "Beforepacks-Installation" 
    $SCRIPT_LOGDAT = $InstallPath | Join-Path -ChildPath "logs" | Join-Path -ChildPath "$SCRIPT_LOG_BASE-$LOGDAT.log"
    Write-Host "Log file generated will be: $SCRIPT_LOGDAT - Please analyze content after process"
    Set-Content -Value "Start of $SCRIPT_LOG_BASE " -Path $SCRIPT_LOGDAT 

    Add-To-Log -line "Initialization update Sage X3 AdxAdmin/Runtime ..."   -errorLevel 0
    Add-To-Log -line "Platform: $([System.Environment]::OSVersion.Platform)"  -errorLevel 0    
    Add-To-Log -line "PowerShell: $($PSVersionTable.PSVersion)" -errorLevel 0 # Get the PowerShell version

    Add-To-Log -line "Check Sage X3 processes"  -errorLevel 0

    # Linux:
    #
    # cd "${INSTALL_PATH}"
    # $SHELL servicestop.sh
    # $SHELL servicedelete.sh
    # pkill -f sadfsq
    # pkill -f adxdsrv
    # pkill -f adxd
    # if [ -f "SAGE ERP X3 EULA FR".txt ]; then rm -f "SAGE ERP"*.txt; fi
    # if [ -f "SAGE ERP X3 EULA FR".htm ]; then rm -f "SAGE ERP"*.htm; fi

    # MS Windows:
    #
    # REM taskkill /im sadfsq.exe /f /t
    # REM taskkill /im adxdsrv.exe /f /t
    # REM taskkill /im adxd.exe /f /t

    Kill-AdxProcess -ProcessName "sadfsq"  -StartWithPath $InstallPath
    Kill-AdxProcess -ProcessName "adxdsrv"  -StartWithPath $InstallPath
    Kill-AdxProcess -ProcessName "adxd"  -StartWithPath $InstallPath

    Add-To-Log -line  "Done" -errorLevel 0
}
catch {

    if ($null -ne $SCRIPT_LOGDAT) {
        Add-To-Log -line ($Error[0] | Out-String)  -errorLevel 1
        Add-To-Log -line "Stack Trace: " -file $SCRIPT_LOGDAT -errorLevel 0
        Add-To-Log -line ($PSItem.ScriptStackTrace | Out-String) -file $SCRIPT_LOGDAT -errorLevel 0
        Add-To-Log -line " " -file $SCRIPT_LOGDAT -errorLevel 2
    }
    else {
        throw $Error[0]
    }
    $Error.Clear()
}