#Requires -RunAsAdministrator
#
<# ###########################################################
# beforepacks.ps1
# X3 V12 - PowerShell Script to prepare Console Update
#
# Clean old exe files, dll files, old directories, ..
#
# INPUT PARAMETERS : 1 mandatory
#   Parameter 1 : -InstallPath [ex: "C:\Sage\SafeX3\Console"]
# ex:
# Powershell.exe -executionpolicy remotesigned -File  .\beforepacks.ps1
###########################################################>

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 {
    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 Remove-Filename {
    param(
        [Parameter(Mandatory = $true, Position = 1)] [Array] $FilenamesToDelete
    )
    Add-To-Log -line  "Deleting files: $FilenamesToDelete" -errorLevel 0
    foreach ($FilenameToDelete in $FilenamesToDelete) {

        $fullname = $InstallPath | Join-Path -ChildPath $FilenameToDelete
        if (Test-Path $fullname) {
            Remove-Item -Path $fullname
            Add-To-Log -line  "$fullname deleted" -errorLevel 0
        }    
    }
    Add-To-Log -line  "Deletion finished ( $FilenamesToDelete )" -errorLevel 0
}


function Clean-Previous-Version {

    $ListFilesToDelete = @(
        ".installationinformation",
        "SAGE ERP*.txt", 
        "SAGE ERP*.htm", 
        "*.exe", 
        "*.dll", 
        "*.pdb"
        "*.config", 
        "modules", 
        "resources")

    foreach ($filter in $ListFilesToDelete) { 
        $filenames = Join-Path -Path $InstallPath -ChildPath $filter 
        Add-To-Log -line  "Deleting  $filenames"  -errorLevel 0
        Remove-Item -Path $filenames  -Recurse  -ErrorAction SilentlyContinue
    }

}

function Clean-Registry {

    # until Version 2.42: "Sage Safe X3 Management Console"

    $ListRegistry = @(
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\SAFE X3 V2 Management Console",
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Sage Safe X3 Management Console"
    )
    foreach ($registry in $ListRegistry) { 
        $reg = Get-Item -path $registry  -ErrorAction SilentlyContinue
        if ($reg) {
            Add-To-Log -line  "Deleting registry $registry"  -errorLevel 0
            Remove-Item -Path $registry -Recurse   -ErrorAction SilentlyContinue   
        }
    }



}

function Clean-Previous-Lnk {
      
    $ListLnkToDelete = @(
        "\Microsoft\Windows\*Sage Safe X3 Management Console*.lnk",
        "\Microsoft\Windows\*Console de configuration Safe X3 V2*.lnk", 
        "\Microsoft\Windows\*Console de configuration Sage EM*.lnk", 
        "\Microsoft\Windows\*SAFE X3 V2 Management Console*.lnk",
        "\Microsoft\Windows\Start Menu\Programs\Sage\Console Sage Safe X3")

    $ListLnkToDelete2 = @(
        "*Sage Safe X3 Management Console*.lnk",
        "*Console de configuration Safe X3 V2*.lnk", 
        "*Console de configuration Sage EM*.lnk",
        "*SAFE X3 V2 Management Console*.lnk")
    
    foreach ($filter in $ListLnkToDelete) { 
        $filenames = Join-Path -Path $env:LOCALAPPDATA -ChildPath $filter 
        Add-To-Log -line  "Deleting  $filenames"  -errorLevel 0
        Remove-Item -Path $filenames  -Recurse  -ErrorAction SilentlyContinue
        $filenames = Join-Path -Path $env:ALLUSERSPROFILE -ChildPath $filter 
        Add-To-Log -line  "Deleting  $filenames"  -errorLevel 0
        Remove-Item -Path $filenames  -Recurse  -ErrorAction SilentlyContinue
    }
    foreach ($filter in $ListLnkToDelete2) { 
        $filenames = Join-Path -Path $env:USERPROFILE -ChildPath $filter 
        Add-To-Log -line  "Deleting  $filenames"  -errorLevel 0
        Remove-Item -Path $filenames  -Recurse  -ErrorAction SilentlyContinue

        $filenames = Join-Path -Path $env:PUBLIC -ChildPath $filter 
        Add-To-Log -line  "Deleting  $filenames"  -errorLevel 0
        Remove-Item -Path $filenames  -Recurse  -ErrorAction SilentlyContinue
    }
}

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

    $LOGDAT = Get-Formatted-Date
    $SCRIPT_LOG_BASE = "Beforepacks-Installation" 
    $SCRIPT_LOGDAT = $InstallPath | 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 Console ..."   -errorLevel 0

    # cd C:\Dev\X3\configuration-console257\installers\izpack\X3Console\project\updatescripts
    #.\beforepacks.ps1 -InstallPath  "C:\Sage\SafeX3\Console"
    Add-To-Log -line "Clean previous files"  -errorLevel 0
    Clean-Previous-Version
    if (-NOT $isLinux) {
        # Windows 
        Clean-Registry
        Clean-Previous-Lnk
    }
    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()
}