Greyhound.psm1

<##############################################################
                    helper functions
##############################################################>



function Get-MySqlVersion {
    [CmdletBinding()]
    param (
        [String]$MySqlServiceName='MySql'
    )
    try {
        $MySqlService = Get-WmiObject win32_service | Where-Object Name -eq $MySqlServiceName
        if ($MySqlService) {
            [string]$MySqldExePath = $MySqlService.PathName -replace '^"?(.*mysqld).*', '$1.exe'   
            if ($MySqldExePath) {
                $MySqldExe = Get-Item -Path $MySqldExePath -ErrorAction Stop
            } else {
                Throw "Der MySqld-Pfad konnte nicht ermittelt werden"
            }           
        }
        $MySqldExe.VersionInfo
    }
    catch {
        Write-Error "Es ist ein Fehler bei der Ermittlung der MySQL-Version aufgetreten: $($_.Exception.Message)" 
    }
}



function Get-MySqlBasedir {
    [CmdletBinding()]
    param (
        [String]$MySqlServiceName='MySql'
    )
    try {
        $MySqlService = Get-WmiObject win32_service | Where-Object Name -eq $MySqlServiceName
        if ($MySqlService) {
            [string]$MySqlBaseDir = $MySqlService.PathName -replace '^"?(.*)\\bin\\.*exe.*', "`$1"
        }
        $MySqlBaseDir
    }
    catch {
        Write-Error "Es ist ein Fehler bei der Ermittlung des MySQL-Installationspfades aufgetreten: $($_.Exception.Message)" 
    }
}



function Get-MySqlMyIni {
    [CmdletBinding()]
    param (
        [String]$MySqlServiceName='MySql'
    )
    try {
        $MySqlService = Get-WmiObject win32_service | Where-Object Name -eq $MySqlServiceName
        if ($MySqlService) {
            [string]$MySqlMyIni = $MySqlService.PathName -replace '.*--defaults-file=(.*\.ini).*', "`$1"
        }
        $MySqlMyIni
    }
    catch {
        Write-Error "Es ist ein Fehler bei der Ermittlung des MySQL-Ini-Pfades aufgetreten: $($_.Exception.Message)" 
    }
}



function Get-MySqlDatadir {
    [CmdletBinding()]
    param (
        [String]$MySqlServiceName='MySql'
    )
    try {
        $MySqlService = Get-WmiObject win32_service | Where-Object Name -eq $MySqlServiceName
        if ($MySqlService) {
            [string]$MySqlMyIni = $MySqlService.PathName -replace '.*--defaults-file=(.*\.ini).*', "`$1"
        }
        $Value = 'datadir'
        $MySqlDatadir = (((Get-Content $MySqlMyIni | Select-String -Pattern "$Value=") -replace '[\r\n]') -replace "$Value=") -replace "/", "\"
        $MySqlDatadir
    }
    catch {
        Write-Error "Es ist ein Fehler bei der Ermittlung des MySQL-Data-Pfades aufgetreten: $($_.Exception.Message)"
    }
}



function Get-MySqlVariables {
    [CmdletBinding()]
    param (
        [string]$VariableName,
        [string]$MySqlServiceName='MySql',
        [string]$MySqlHostname='localhost',
        [string]$MySqlUser='root',
        [string]$MySqlPass=''
    )
    try {
        Clear-Variable MySqlVariables -ErrorAction SilentlyContinue
        $QueryResult = (Invoke-MySqlQuery -MySqlQuery "SHOW VARIABLES" -MySqlUser $MySqlUser -MySqlPass $MySqlPass) -replace '\t', '='
        if ($QueryResult) {
            $QueryResult | ForEach-Object {
                $MySqlVariables += ConvertFrom-StringData -StringData ($_ -replace '[\r\n]')
            }
        }
        
        if ($VariableName) {
            $MySqlVariables.$VariableName
        } else {
            $MySqlVariables
        }
    }
    catch {
        Write-Error "Es ist ein Fehler bei der Abfrage der MySql-Variablen aufgetreten: $($_.Exception.Message)"
    }
}



function Get-GreyhoundInstallPath {
    try {
        $GreyhoundInstallPath = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Greyhound' -Name InstallLocation -ErrorAction SilentlyContinue).InstallLocation
        if (($GreyhoundInstallPath) -and (Test-Path $GreyhoundInstallPath)) {
            $GreyhoundInstallPath
        } else {
            return $null
        }
    }
    catch {
        Write-Error "Es ist ein Fehler bei der Ermittlung des GREYHOUND Installationspfades aufgetreten: $($_.Exception.Message)"
    }
}



<#
.SYNOPSIS
    Ermittelt die Version der GREYHOUND-Installation
.DESCRIPTION
    Ermittelt die Version der GREYHOUND-Installation
.EXAMPLE
    Example of how to use this cmdlet
#>

function Get-GreyhoundVersionInfo {
    try {
        $GreyhoundServerExe = (Get-GreyhoundInstallPath) + 'Server\GreyhoundServer.exe'
        if (Test-Path -Path $GreyhoundServerExe) {
            $Version = (Get-Item $GreyhoundServerExe).VersionInfo.ProductVersionRaw
            $Version
        } else {
            Throw "GREYHOUND ist nicht installiert"
        }   
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function Invoke-GreyhoundAdmin {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false)]
        [Switch]$Start,
        [Switch]$Stop
    )
   
    try {
        $GreyhoundAdmin = (Get-GreyhoundInstallPath) + 'Server\GreyhoundAdmin.exe'
        if (!(Test-Path $GreyhoundAdmin)) {
            Throw "Der GREYHOUND Admin wurde nicht gefunden"
        }

        if ($Start) {
            if ((Start-Process -FilePath "$GreyhoundAdmin" -ArgumentList "-Start -NoGui" -Wait -NoNewWindow -PassThru).Exitcode -gt 0) {
                Throw "Der GREYHOUND Admin hat einen ExitCode ausgegeben"
            }
        } elseif ($Stop) {
            if ((Start-Process -FilePath "$GreyhoundAdmin" -ArgumentList "-Stop -NoGui" -Wait -NoNewWindow -PassThru).Exitcode -gt 0) {
                Throw "Der GREYHOUND Admin hat einen ExitCode ausgegeben"
            }
        }

    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function Restart-GreyhoundServer {
    try {
        Invoke-GreyhoundAdmin -Stop
        Invoke-GreyhoundAdmin -Start           
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function Get-GreyhoundSystemPassword {
    try {
        $GreyhoundServerIni = (Get-GreyhoundInstallPath) + 'Server\GreyhoundServer.ini'
        if (Test-Path $GreyhoundServerIni) {
            $GreyhoundSystemPassword = (Get-Content $GreyhoundServerIni | Select-String -Pattern 'SystemPassword' -SimpleMatch | ConvertFrom-StringData).SystemPassword
            $GreyhoundSystemPassword
        } else {
            Write-Verbose "Die GREYHOUND Serverkonfiguration `"$GreyhoundServerIni`" wurde nicht gefunden."
        }           
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



<#
.SYNOPSIS
    Zeigt die Einstellungen des GREYHOUND-Servers an
.DESCRIPTION
    Ohne Parameter liefert dieses Cmdlet alle Werte der GreyhoundServer.ini. Wird nur ein bestimmter Wert benötigt, so kann dieser explizit ueber den Key angegeben werden.
#>

function Get-GreyhoundServerIniValue {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false)]
        [String]$Key,
        [Parameter(ParameterSetName='MySQL')]
        [String]$Compression,
        [ValidateSet('MySQL', 'Global', 'LogFile', 'HtmlInline', 'IndexServer', 'AppServer', 'QueueServer',
            'AntiSpam', 'OCR', 'AccessServer', 'DataExchangeServer', 'SyncServer', 'AddOnServer', 'ItemCount',
            'CommServer', 'AutoClassificationServer')][String]$Section
    )

    try {
        $GreyhoundServerIni = (Get-GreyhoundInstallPath) + 'Server\GreyhoundServer.ini'
        if (Test-Path $GreyhoundServerIni) {
            if (!$Key) {
                $Result = Get-Content $GreyhoundServerIni
            } else {
                $Result = (Get-Content $GreyhoundServerIni | Select-String "^$Key=" | ConvertFrom-StringData).$Key
            }
            $Result
        } else {
            Write-Verbose "Die GREYHOUND Serverkonfiguration `"$GreyhoundServerIni`" wurde nicht gefunden."
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function Get-GreyhoundSetup {
    [CmdletBinding()]
    [Alias("Get-GreyhoundServerSetup", "Get-MariaDBSetup")]
    param (
        [string]$DownloadDir=$PWD.Path,
        [string]$BaseUrl = 'https://greyhound-software.com/files/greyhound',
        [ValidateSet('GreyhoundSetup', 'GreyhoundAspSetup', 'MariaDBSetup')]
        [string]$Type = 'GreyhoundSetup',
        [ValidateSet('Stable', 'Beta', 'Test')]
        [string]$Edition = 'Stable',
        # the following two switches are deprecated. Use "Edition" parameter instead.
        [switch]$Beta,
        [switch]$Test
    )

    if ($Beta) {
        $Edition = "Beta"
    } elseif ($Test) {
        $Edition = "Test"
    }

    try {
        switch -Wildcard ($Type) {
            'Greyhound*' {
                switch ($Edition) {
                    'Stable' {$SetupName = "${Type}.exe"}
                    'Beta' {$SetupName = "${Type}Beta.exe"}
                    'Test' {$SetupName = "${Type}Test.exe"}    
                }
            }
            'MariaDBSetup' {
                $SetupName = "${Type}.msi"
            }
        }
    
        $RemoteFile = "$BaseUrl/$SetupName"
        $LocalFile = $DownloadDir.TrimEnd('\') + '\' + $SetupName
    
        if (Test-Path $LocalFile) {
            [Int64]$RemoteFileSize = (Invoke-WebRequest -Uri $RemoteFile -Method Head -UseBasicParsing).Headers.'Content-Length'
            [Int64]$LocalFileSize = (Get-Item $LocalFile).Length

            Write-Verbose "LocalFileSize: $LocalFileSize RemoteFileSize: $RemoteFileSize"
   
            if ($RemoteFileSize -gt 0 -and $LocalFileSize -gt 0) {
                if ($RemoteFileSize -ne $LocalFileSize) {
                    Start-BitsTransfer -Source $RemoteFile -Destination $LocalFile -Description "Downloading $RemoteFile"
                } else {
                    Write-Verbose "Die Datei `"$SetupName`" mit einer Dateigroesse von $RemoteFileSize Bytes existiert bereits."
                }
            } else {
                Throw "Es ist ein Fehler beim Dateigroessenvergleich aufgetreten."
            }
        } else {
            Start-BitsTransfer -Source $RemoteFile -Destination $LocalFile -Description "Downloading $RemoteFile"
        }
    
        if (Test-Path $LocalFile) {
            $LocalFile
        } else {
            Throw "Es ist ein Fehler beim Herunterladen der Datei '$RemoteFile' aufgetreten."
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function Get-WindowsServerFiles {
    [CmdletBinding()]
    param (
        [string]$DownloadDir=$env:TEMP,
        [string]$BaseUrl = 'https://greyhound-software.com/files/greyhound/tools',
        [string]$FileListUrl = "$BaseUrl/WindowsServerSetup.txt"
    )

    try {
        $DownloadDir = $DownloadDir.TrimEnd('\')
        if (!(Test-Path -Path $DownloadDir -PathType Container)) {
            Throw "Das Downloadverzeichnis `"$DownloadDir`" existiert nicht."
        }
        try {
            $WindowsSetupFiles = (Invoke-WebRequest -URI "$FileListUrl").Content -split "`r`n|`n" | ConvertFrom-String -Delimiter '=' -PropertyNames 'Type', 'Source'
            
            if (!($WindowsSetupFiles)) {
                Throw "Die Liste der herunterzuladenden Dateien existiert nicht oder ist leer."
            }

            Write-Verbose "Die Dateiliste wird erstellt..."
            for ($i=0; $i -le $WindowsSetupFiles.Length -1; $i++) {
                $FilenameWithoutPath = ''
                
                if ($WindowsSetupFiles[$i].Source.Length -gt 0 -and $WindowsSetupFiles[$i].Source.LastIndexOf('/') -gt 0) {
                    $FilenameWithoutPath = $WindowsSetupFiles[$i].Source.Substring($WindowsSetupFiles[$i].Source.LastIndexOf('/') + 1)
                } elseif ($WindowsSetupFiles[$i].Source.Length -gt 0 -and $WindowsSetupFiles[$i].Source.LastIndexOf('/') -eq 0) {
                    $FilenameWithoutPath = $WindowsSetupFiles[$i].Source
                }

                if ($FilenameWithoutPath) {
                    $WindowsSetupFiles[$i] | Add-Member -NotePropertyName 'Destination' -NotePropertyValue "$DownloadDir\$FilenameWithoutPath"
                    if (Test-Path $WindowsSetupFiles[$i].Destination) {
                        # file already exists, check filesize
                        [Int64]$RemoteFileSize = (Invoke-WebRequest -Uri $WindowsSetupFiles[$i].Source -Method Head -UseBasicParsing).Headers.'Content-Length'
                        [Int64]$LocalFileSize = (Get-Item "$DownloadDir\$FilenameWithoutPath").Length
            
                        Write-Verbose "LocalFileSize: $LocalFileSize RemoteFileSize: $RemoteFileSize"

                        if ($RemoteFileSize -gt 0 -and $LocalFileSize -gt 0) {
                            if ($RemoteFileSize -ne $LocalFileSize) {
                                $WindowsSetupFiles[$i] | Add-Member -NotePropertyName 'Download' -NotePropertyValue $true
                            } else {
                                Write-Verbose "Die Datei `"$DownloadDir\$FilenameWithoutPath`" mit einer Dateigroesse von $RemoteFileSize Bytes existiert bereits und wird aus der Downloadliste ausgenommen."
                            }
                        } else {
                            Throw "Es ist ein Fehler beim Dateigroessenvergleich aufgetreten."
                        }
                    } else {
                        # file doesn't exist, add to list
                        $WindowsSetupFiles[$i] | Add-Member -NotePropertyName 'Download' -NotePropertyValue $true
                    }
                }
            }

            if ($WindowsSetupFiles | Where-Object Download -eq $true) {
                Write-Verbose "Der Download der Dateien wird gestartet..."
                Start-BitsTransfer -Source ($WindowsSetupFiles | Where-Object Download -eq $true).Source -Destination ($WindowsSetupFiles | Where-Object Download -eq $true).Destination -Description "Downloading Files"
            }

            $WindowsSetupFiles | Select-Object Type, Source, Destination
        }
        catch {
            Write-Error "Es ist ein Fehler bei der Erstellung der Downloadliste aufgetreten: $($PSItem.ToString())"
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function New-GreyhoundVhdx (
    [PSCustomObject]$WindowsSetupFiles,
    [string]$VhdPath=$PWD.Path + '\GHSRV_C.vhdx',
    [string]$Edition=1,
    [string]$DiskLayout='UEFI',
    [switch]$DeleteSource,
    [Int64]$SizeBytes=128GB
    ) {

    Write-Host Debug $WindowsSetupFiles
    
    $VhdParams = @{
        SourcePath = ($WindowsSetupFiles | Where-Object Type -eq 'Iso').Destination
        UnattendPath = ($WindowsSetupFiles | Where-Object Type -eq 'Xml').Destination
        VhdPath = $VhdPath
        Edition = $Edition
        DiskLayout = $DiskLayout
    }

    try {
        if (Test-Path $VhdParams.VhdPath) {
            Throw "Die Datei `"$VhdParams`" exisitiert bereits."
        }

        Convert-WindowsImage -SourcePath $VhdParams.SourcePath -DiskLayout $VhdParams.DiskLayout -VhdPath $VhdParams.VhdPath -Edition $VhdParams.Edition -UnattendPath $VhdParams.UnattendPath | Out-Null
        if ($DeleteSource) {
            Remove-Item $SourcePath, $UnattendPath
        }

        if (Test-Path $VhdParams.VhdPath) {
            $VhdParams.VhdPath
        } else {
            Throw "Es ist ein Fehler bei der Konvertierung der ISO-Datei in VHDx-Datei aufgetreten."
        }
    }
    catch {
        Write-Error $($PSItem.ToString()) -Category ObjectNotFound
    }
}



<#
.SYNOPSIS
    Erstellt eine neue VM fuer die Einrichtung einer neuen GREYHOUND Installation
.DESCRIPTION
    Erstellt eine neue VM fuer die Einrichtung einer neuen GREYHOUND Installation. Dabei wird der erste verfügbare VMSwitch vom Typ "Extern" verwendet. Optional kann eine bereits bestehende VHD angegeben werden. Fehlt dieser Angabe, dann wird eine neue VHD erzeugt.
    Nach der Erstellung werden die Daten der VM in ein eigenes Verzeichnis unterhalb des Standard-Pfades des VMHost verschoben, sodass alle Dateien beisammen sind.
#>

function New-GreyhoundVM {
    [CmdletBinding()]
    Param (
        # Just some help
        [Parameter(Mandatory=$true)]
        [String]$VmName,
        [Parameter(Mandatory=$false, ValueFromPipeline=$true)]
        [String]$VhdPath,
        [String]$VmNotes,
        [String]$VmSwitchName=(Get-VMSwitch | Where-Object {$_.SwitchType -eq 'External' -and `
            (Get-NetAdapter -InterfaceDescription $_.NetAdapterInterfaceDescription | Where-Object Status -eq 'Up')}).Name,
        [Int64]$VmVHDSize=64GB,
        [String]$VmBasePath= (Get-VMHost).VirtualMachinePath + '\' + $VmName,
        [Int]$VmGeneration=2,
        [Int]$VMProcessorCount=4,
        [Int64]$VmMemoryStartupBytes=8GB,
        [Int64]$VmMemoryMinimumBytes=8GB,
        [Int64]$VMMemoryMaximumBytes=8GB,
        [string]$DiskLayout='UEFI',
        [ValidateSet('Windows Server 2019 Standard Core', 'Windows Server 2019 Standard Gui', 'Windows Server 2019 Datacenter Core', 'Windows Server 2019 Datacenter Gui')][String]$WindowsEdition='Windows Server 2019 Standard Core'
    )

    try {
        if (!($VmSwitchName)) {
            Throw "Es wurde kein aktiver, externer, virtueller Switch gefunden."
        }

        if (!($VhdPath)) {
            Write-Verbose "Eine neue VHD auf Basis von $WindowsEdition wird erstellt..."
            switch ($WindowsEdition) {
                'Windows Server 2019 Standard Core' {$Edition = '1'}   
                'Windows Server 2019 Standard Gui' {$Edition = '2'}
                'Windows Server 2019 Datacenter Core' {$Edition = '3'}
                'Windows Server 2019 Datacenter Gui' {$Edition = '4'}
            }
            $VhdPath = New-GreyhoundVhdx(Get-WindowsServerFiles) -Edition $Edition -SizeBytes $VmVHDSize -DiskLayout $DiskLayout
        }
        
        if (Test-Path $VHDPath) {
            Write-Verbose "Eine neue VM wird erstellt..."
            New-VM -Name $VmName -Generation $VmGeneration -SwitchName $VmSwitchName -VHDPath $VHDPath |
                Set-VM -ProcessorCount $VMProcessorCount -DynamicMemory -MemoryStartupBytes $VmMemoryStartupBytes -MemoryMinimumBytes $VmMemoryMinimumBytes -MemoryMaximumBytes $VMMemoryMaximumBytes -Notes $VmNotes -Passthru |
                Move-VMStorage -DestinationStoragePath $VmBasePath
            Get-VM -Name $VmName
        } else {
            Throw "Der Pfad zur VHD-Datei ist ungueltig."
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



<#
.SYNOPSIS
    Installiert MariaDB in einer Silent-Installation
.DESCRIPTION
    Installiert MariaDB in einer Silent-Installation. Die Setupdatei kann auch via Pipeline in Kombination mit Get-MariaDBSetup verwendet werden.
.EXAMPLE
    Get-MariaDBSetup | Install-MariaDBSetup -Password 'MyRootPassword'
#>

function Install-MariaDB {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true,
        ValueFromPipeline=$true)]
        [String]$SetupFile,
        [Parameter(Mandatory=$false)]
        [String]$ServiceName='MySql',
        [Switch]$AllowRemoteRootAccess,
        [Boolean]$SkipNetworking,
        [String]$Password,
        [Switch]$NoServiceInstall
    )

    $SetupFile = Resolve-Path($SetupFile)
    if (!(Test-Path -Path $SetupFile)) {
        Write-Error "Die Datei '$SetupFile' wurde nicht gefunden." -Category ObjectNotFound
        Break
    }

    $Command = (Get-Command 'msiexec').Path
    $Arguments = @(
        "/package",
        "`"$SetupFile`"",
        "/qn"
    )

    if ($Password) {
        $Arguments += @("PASSWORD=$Password")
    }

    if (!($NoServiceInstall)) {
        "SERVICENAME=$ServiceName"
    }

    if ($AllowRemoteRootAccess) {
        $Arguments += @("ALLOWREMOTEROOTACCESS=True")
    } else {
        $Arguments += @("ALLOWREMOTEROOTACCESS=False")
    }

    Write-Host "Die Datei $SetupFile wird mit den Argumenten $Arguments installiert..."

    try {
        $CommandBasename = $Command.Substring($Command.LastIndexOf('\') + 1, $Command.LastIndexOf('.') - $Command.LastIndexOf('\') - 1)
        $StdOutFile = "$env:TEMP\$CommandBasename.stdout"
        $StdErrFile = "$env:TEMP\$CommandBasename.stderr"

        if ((Start-Process -FilePath "$Command" -ArgumentList "$Arguments" -RedirectStandardOutput $StdOutFile -RedirectStandardError $StdErrFile -Wait -PassThru).ExitCode -eq 0) {
            Get-Content $StdOutFile
        } else {
            (Get-Content $StdErrFile)
            Throw "Es ist ein Fehler bei der Installation aufgetreten. StdOut: " + (Get-Content $StdErrFile)
        }
    } catch {
        Write-Error "Es ist ein Fehler bei der Ausführung des Befehls '$Command $Arguments' aufgetreten: $($PSItem.ToString())"
    }
    finally {
        Remove-Item $StdOutFile -Force -ErrorAction SilentlyContinue
        Remove-Item $StdErrFile -Force -ErrorAction SilentlyContinue 
    }
}



<#
.SYNOPSIS
    Installiert GREYHOUND in einer Silent-Installation
.DESCRIPTION
    Installiert GREYHOUND in einer Silent-Installation. Die Setupdatei kann auch via Pipeline in Kombination mit Get-GreyhoundServerSetup verwendet werden. Saemtliche Optionen des GUI-Setups können in diesem Cmdlet als Parameter übergeben werden.
    Für eine Serverinstallation sind die Angaben einer Vertragsnummer und einer Seriennummer obligatorisch.
.EXAMPLE
    GreyhoundServerSetup | Install-GreyhoundServer
#>

function Install-GreyhoundServer {
    [CmdletBinding()]
    [Alias("Update-GreyhoundServer")]
    param (
        [Parameter(Mandatory=$true,
        ValueFromPipeline=$true)]
        [String]$SetupFile,
        [Parameter(Mandatory=$false)]
        [String]$ContractNumber,
        [String]$SerialNumber,
        [ValidateSet('Complete', 'Server', 'Client')][String]$Kind='Server',
        [String]$TargetDir="${env:ProgramFiles(x86)}\GREYHOUND\",
        [Switch]$DesktopShortcut=$false,
        [Switch]$StartMenuShortcut=$false,
        [Switch]$QuicklaunchShortcut=$false,
        [Switch]$DefaultMailClient=$false,
        [Switch]$PrinterDriver=$false,
        [Switch]$NoStart=$false,
        [String]$DatabaseUser='root',
        [String]$DatabasePass,
        [int16]$DatabasePort=3306,
        [ValidateSet('Small', 'Medium', 'Large')][String]$DatabaseTemlate='Large',
        [String]$AdminPassword='admin',
        [Switch]$Force=$false
    )

    try {
        $SetupMode = ''

        $SetupFile = Resolve-Path($SetupFile)
        if (Test-Path -Path $SetupFile) {
            $SetupVersion = (Get-Item $SetupFile).VersionInfo.ProductVersionRaw
            $Command = $SetupFile
        } else {
            Write-Error "Die Datei '$SetupFile' wurde nicht gefunden." -Category ObjectNotFound
            Break
        }

        if (!($Force) -and (Get-GreyhoundInstallPath)) {
            $SetupMode = 'Update'
            try {
                $InstalledVersion = Get-GreyhoundVersionInfo
                
                if ($InstalledVersion -gt $SetupVersion) {
                    Write-Host "Die installierte GREYHOUND-Version $InstalledVersion ist neuer als die Installationsdatei $SetupVersion." 
                    if (!($Force)) {
                        Break
                    }
                } elseif ($InstalledVersion -eq $SetupVersion) {
                    Write-Host "GREYHOUND Version $InstalledVersion ist bereits installiert." 
                    if (!($Force)) {
                        Break
                    }
                } else {
                    Write-Verbose "Die Installationsdatei $SetupVersion hat eine neuere Version als die installierte GREYHOUND-Version $InstalledVersion."
                }
    
                [String]$ContractNumber = Get-GreyhoundServerIniValue -Key 'ContractNumber'
                [String]$SerialNumber = Get-GreyhoundServerIniValue -Key 'Serial'

                Write-Verbose "Aktuelle Vertragsnummer: $ContractNumber"
                Write-Verbose "Aktuelle Seriennummer: $SerialNumber"
    
                $Arguments = @(
                    "-silent",
                    "-contract", "`"$ContractNumber`"",
                    "-serial", "`"$SerialNumber`"",
                    "-kind", "$Kind"
                )                  
            }
            catch {
                Write-Error "Es ist ein Fehler bei der Versionsermittlung aufgetreten."
            }
        } else {
            $SetupMode = 'Install'

            $Arguments = @(
                "-silent",
                "-contract", "`"$ContractNumber`"",
                "-serial", "`"$SerialNumber`"",
                "-kind", "$Kind",
                "-targetdir", "`"$TargetDir`"",
                "-databaseuser", "$DatabaseUser",
                "-databaseport", "$DatabasePort"
                "-databasetemplate", "$DatabaseTemlate",
                "-adminpassword", "$AdminPassword"
            )

            if ($DatabasePass) {
                $Arguments += @("-databasepass", "$DatabasePass")
            }
        
            if ($NoStart) {
                $Arguments += @("-nostart")
            }

            if (!$DesktopShortcut) {
                $Arguments += @("-nodesktop")
            }

            if (!$StartMenuShortcut) {
                $Arguments += @("-nostartmenu")
            }

            if (!$QuicklaunchShortcut) {
                $Arguments += @("-noquicklaunch")
            }

            if (!$DefaultMailClient) {
                $Arguments += @("-nodefaultmail")
            }

            if (!$PrinterDriver) {
                $Arguments += @("-noprinterdriver")
            }
        }

        if ($ContractNumber -and $SerialNumber) {
            if ($SetupMode -eq 'Install') {
                Write-Host "GREYHOUND Version $SetupVersion wird installiert..."
                Write-Verbose "Zielverzeichnis: `"$TargetDir`""
            } else {
                $VersionInstalled = (Get-GreyhoundVersionInfo).ToString()
                Write-Host "Die GREYHOUND-Installation wird von Version $VersionInstalled auf Version $SetupVersion aktualisiert..."
            }
            if ((Start-Process -FilePath "$Command" -ArgumentList "$Arguments" -Wait -PassThru).ExitCode -eq 0) {
                Write-Host "Die GREYHOUND-Installation war erfolgreich."
            } else {
                Throw "Das GREYHOUND-Setup hat einen unbekannten Fehler gemeldet."
            }
        } else {
            Write-Error "Fuer eine Installation sind eine Vertrags- und eine Seriennummer notwendig." -Category NotSpecified
            Break
        }
    }
    catch {
        Write-Error "Es ist ein Fehler bei der GREYHOUND-Installation aufgetreten: $($_.Exception.Message)"
    }
}



function Uninstall-GreyhoundServer {
    try {
        $GreyhoundSetupExe = (Get-GreyhoundInstallPath) + 'GreyhoundSetup.exe'
        if (Test-Path -Path $GreyhoundSetupExe) {
            Write-Host "GREYHOUND wird deinstalliert..."
            if ((Start-Process -FilePath "$GreyhoundSetupExe" -ArgumentList '-uninstall -useregistry -silent' -Wait -NoNewWindow -PassThru).ExitCode -eq 0) {
                Write-Host "GREYHOUND wurde erfolgreich deinstalliert."
            } else {
                Throw "Das GREYHOUND-Setup hat einen unbekannten Fehler gemeldet."
            }
        } else {
            Write-Error "Die Datei `"$GreyhoundSetupExe`" ist nicht vorhanden." -Category ObjectNotFound
            Break
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



<#
.SYNOPSIS
    Erstellt einen Dump der GREYHOUND Datenbank
.DESCRIPTION
    Erstellt einen Dump der GREYHOUND Datenbank. Optional kann dieser direkt komprimiert werden.
#>

function New-GreyhoundDatabaseDump {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false,
        ValueFromPipeline=$true)]
        [string]$MySqlUser='root',
        [string]$MySqlPassword,
        [string]$MySqlParameters='--default-character-set=latin1',
        [string]$MySqlDatabase='greyhound',
        [switch]$Compress,
        [string]$DestinationPath=$PWD.Path
    )

    $MySqlService = Get-WmiObject win32_service | Where-Object Name -eq 'MySql'
    $MySqlDump = $MySqlService.PathName.Split('mysqld.exe')[0] + 'mysqldump.exe'

    $StdErr = $env:TEMP + '\mysql.stderr'
        
    if (!(Test-Path -Path $MySqlDump)) {
        Write-Warning 'Die Exe-Datei' $MySqlDump 'wurde nicht gefunden.'
        Break
    }

    $MySqlDumpArgs = @(
        "--user=$MySqlUser"
    )

    if ($MySqlPassword) {
        $MySqlDumpArgs += @(
            "--password=$MySqlPassword"
        )
    }
    
    $MySqlDumpArgs += @(
        "--default-character-set=latin1",
        "$MySqlDatabase"
    )

    try {
        [string]$SqlFile = $DestinationPath + '\' + $MySqlDatabase + '.sql'
        if ((Start-Process -FilePath $MySqlDump -ArgumentList $MySqlDumpArgs -RedirectStandardOutput $SqlFile -RedirectStandardError $StdErr -Wait -NoNewWindow -PassThru).Exitcode -gt 0) {
            if (Test-Path -Path $StdErr) {
                $ExceptionText = Get-Content $StdErr
                Remove-Item $StdErr
            }
            Throw $ExceptionText
        } else {
            Write-Host $SqlFile
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
    finally {
        Remove-Item $SqlFile -ErrorAction SilentlyContinue
    }

    if ($Compress) {
        if (Test-Path -Path $SqlFile) {
            $Zip = (Get-Item  $SqlFile).DirectoryName + '\' + (Get-Item  $SqlFile).BaseName + '.zip'
            if (Test-Path -Path $Zip) {
                Remove-Item $Zip
            }
            
            try {
                Write-Verbose "Der Datenbank-Dump wird komprimiert. Ziel: $Zip"
                Compress-Archive -Path $SqlFile -DestinationPath $Zip -CompressionLevel Optimal
            }
            catch {
                Write-Error "Es ist ein Fehler beim Komprimieren des Datenbank-Dumps aufgetreten."
            }
            finally {
                Write-Verbose "Die Datei $SqlFile wird gelöscht."
                Remove-Item $SqlFile 
            }

        } else {
            Write-Warning "Die Datenbank-Datei $SqlFile konnte nicht komprimiert werden, weil sie nicht vorhanden ist."
        }
    }
}



<#
.SYNOPSIS
    Fuert beliebige Sql-Abfragen aus.
.DESCRIPTION
    Dieses Cmdlet ist ein Wrapper für mysql.exe einer bestehenden MySQL- oder MariaDB-Installation. Die gewuenschte Abfrage kann als Parameter eingeschlossen in doppelten Anführungszeichen übergeben werden. Die Ausgabe von mysql.exe wird in der Konsole ausgegeben.
#>

function Invoke-MySqlQuery {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string]$MySqlQuery,
        [Parameter(Mandatory=$false)]
        [string]$MySqlServiceName='MySql',
        [string]$MySqlHostname='localhost',
        [string]$MySqlUser='root',
        [string]$MySqlPass
    )

    try {
        $MySqlService = Get-WmiObject win32_service | Where-Object Name -eq $MySqlServiceName

        if (!($MySqlService)) {
            Throw "Der Dienst $MySqlServiceName existiert nicht."
        } elseif ($MySqlService.State -ne 'Running') {
            Throw "Der Dienst $MySqlServiceName ist nicht gestartet."
        }

        $MySqlExe = $MySqlService.PathName -replace '^"?(.*\\).*exe.*', "`$1mysql.exe"
        if (!(Test-Path -Path $MySqlExe)) {
            Throw "Die Datei $MySqlExe wurde nicht gefunden."
        }

        $Arguments = @(
            "--host=$MySqlHostname"
            "--user=$MySqlUser"
            '--execute="' + $MySqlQuery + '"'
        )

        if ($MySqlPass) {
            $Arguments += @(
                "--password=$MySqlPass"
            )
        }
    
        $StdOut = "$($env:TEMP)\MySql.stdout"
        $StdErr = "$($env:TEMP)\MySql.stderr"

        Remove-Item $StdOut, $StdErr -Force -ErrorAction SilentlyContinue
    
        Start-Process -FilePath "$MySqlExe" -ArgumentList "$Arguments" -NoNewWindow -Wait -RedirectStandardOutput $StdOut -RedirectStandardError $StdErr
        if (Test-Path -Path $StdOut) {
            Get-Content $StdOut
            Remove-Item $StdOut -Force -ErrorAction SilentlyContinue
        }
        if (Test-Path -Path $StdErr) {
            $StdErrContent = Get-Content $StdErr
            Remove-Item $StdErr -Force -ErrorAction SilentlyContinue
            Throw $StdErrContent
        }           
    } catch {
        Write-Error "Die MySql-Abfrage konnte nicht ausgefuehrt werden: $($_.Exception.Message)"
    }
}



<#
.SYNOPSIS
    Zeigt das letzte Logfile einer GREYHOUND Serverinstalltion an.
.DESCRIPTION
    Zeigt das letzte Logfile einer GREYHOUND Serverinstalltion an.
#>

function Get-GreyhoundLog {
    try {
        $Logfile = Get-ChildItem((Get-GreyhoundInstallPath) + '\Server\Logs\') | Select-Object -Last 1
        Get-Content $Logfile.FullName
    }
    catch {
        Write-Error $_.Exception.Message
    }    
}



<#
.SYNOPSIS
    Loescht die aktuelle GREYHOUND Datenbank
.DESCRIPTION
    Loescht die aktuelle GREYHOUND Datenbank, sodass eine neue, leere Datenbank beim naechsten GREYHOUND Serverstart erstellt wird. Die Dateien im GREYHOUND Data-Verzeichnis werden dabei nicht gelöscht
#>

function Reset-GreyhoundDatabase {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false,
        ValueFromPipeline=$true)]
        [string]$MySqlHostname='localhost',
        [string]$MySqlUser='root',
        [string]$MySqlPass
    )
    try {
        $PrevGreyhoundServerStatus = ((Get-Service GreyhoundService).Status)

        Stop-Service GreyhoundService -ErrorAction Stop
        if (((Get-Service GreyhoundService).Status) -eq 'Stopped') {
            Write-Verbose "Die GREYHOUND Datenbank wird gelöscht..."
            $MySqlQuery = 'DROP DATABASE greyhound;'
            Invoke-MySqlQuery -MySqlQuery $MySqlQuery -MySqlHostname $MySqlHostname -MySqlUser $MySqlUser -MySqlPass $MySqlPass

            Write-Verbose "Die GREYHOUND Dateien werden gelöscht..."
            $ItemsToDelete = Get-ChildItem((Get-GreyhoundInstallPath) + '\Server\') |
                Where-Object Name -In 'AntiSpam', 'Data', 'AutoClassification', 'FulltextIndex', 'GoogleSync', 'ItemCount', 'Logs', 'Share', 'Thumbnails'
            $ItemsToDelete | Remove-Item -Recurse -Force | Out-Null
        } else {
            Throw "Der GREYHOUND-Dienst konnte nicht gestoppt werden."
        }

        if ($PrevGreyhoundServerStatus -eq 'Running') {
            Start-Service GreyhoundService -ErrorAction Stop
            if (((Get-Service GreyhoundService).Status) -ne 'Running') {
                Throw "Der GREYHOUND-Dienst konnte nicht gestartet werden."
            }
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



<#
.SYNOPSIS
    Konfiguriert perfekte Windows-Defender-Ausnahmen fuer den GREYHOUND-Serverbetrieb
.DESCRIPTION
    Konfiguriert perfekte Windows-Defender-Ausnahmen fuer den GREYHOUND-Serverbetrieb. Vorhandene Einstellungen werden dabei nicht gelöscht.
#>

function Add-GreyhoundDefenderPreference {
    try {
        $GreyhoundInstallPath = (Get-GreyhoundInstallPath).TrimEnd('\')
        $MySqlInstallPath = ((Get-ChildItem "${env:ProgramFiles}\Maria*" -Directory).FullName).TrimEnd('\')

        if ($GreyhoundInstallPath) {
            if ($MySqlInstallPath) {
                Add-MpPreference `
                -ExclusionProcess ("$GreyhoundInstallPath\Server\*", "$GreyhoundInstallPath\Server\Plugins\*", "$MySqlInstallPath\*") `
                -ExclusionPath ("$GreyhoundInstallPath\Server", "$MySqlInstallPath\data")
            } else {
                Throw Der MariaDB-Installationspfad wurde nicht gefunden.
            }
        } else {
            Throw Der GREYHOUND-Installationspfad wurde nicht gefunden.
        }
    } catch {
        Write-Error $_.Exception.Message
    }
}



<#
.SYNOPSIS
    Entfernt eine vorhandene MySql-Tabellenpartitionierung einer GREYHOUND 5-Installation
.DESCRIPTION
    Entfernt eine vorhandene MySql-Tabellenpartitionierung einer GREYHOUND 5-Installation und stellt die notwendigen Indizes wieder her. Dieses Cmdlet macht die Aenderungen von New-GreyhoundDatabasePartitioning wieder rueckgaengig.
#>

function Remove-GreyhoundDatabasePartitioning {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false,
        ValueFromPipeline=$true)]
        [string]$MySqlHostname='localhost',
        [string]$MySqlUser='root',
        [string]$MySqlPass
    )
    try {
        # Auf Partitionierung prüfen
        $Path = (Get-MySqlDatadir) + '\greyhound'
        Write-Verbose "GREYHOUND Datenbank-Pfad: $Path"

        if (($Path) -and (Test-Path $Path) -and (Get-ChildItem -Path $Path -Filter 'items#*')) {
            Write-Verbose "GREYHOUND Dienst wird gestoppt..."
            $PrevGreyhoundServerStatus = ((Get-Service GreyhoundService).Status)

            Stop-Service GreyhoundService -ErrorAction Stop
            if (((Get-Service GreyhoundService).Status) -eq 'Stopped') {
                $MySqlQuery =  @'
USE greyhound;
ALTER TABLE `items` REMOVE PARTITIONING;
ALTER TABLE `items` CHANGE `e_state` `e_state` enum('open','new','question','answer','done','forward','draft','rejected') DEFAULT 'open' NOT NULL;
ALTER TABLE `items` CHANGE `e_kind` `e_kind` enum('email','fax','letter','shortmessage','call','appointment','task','note','contact','file') DEFAULT 'email' NOT NULL;
ALTER TABLE `items` ADD INDEX `e_kind` (`e_kind`);
ALTER TABLE `items` ADD INDEX `e_state` (`e_state`);
ALTER TABLE `items` DROP INDEX `PRIMARY`, ADD PRIMARY KEY(`i_id`);
'@

                Write-Verbose "Die MySQL-Abfrage wird ausgefuehrt: $MySqlQuery"
                Invoke-MySqlQuery -MySqlQuery $MySqlQuery -MySqlHostname $MySqlHostname -MySqlUser $MySqlUser -MySqlPass $MySqlPass -Verbose
            } else {
                Throw "Der GREYHOUND-Dienst konnte nicht gestoppt werden."
            }

            if ($PrevGreyhoundServerStatus -eq 'Running') {
                Write-Verbose "GREYHOUND Dienst wird gestartet..."
                Start-Service GreyhoundService -ErrorAction Stop
                if (((Get-Service GreyhoundService).Status) -ne 'Running') {
                    Throw "Der GREYHOUND-Dienst konnte nicht gestartet werden."
                }
            }
        } else {
            Write-Host "Die GREYHOUND-Datenbank ist nicht partitioniert. Keine Aktion erforderlich."
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function New-GreyhoundDatabasePartitioning {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false,
        ValueFromPipeline=$true)]
        [string]$MySqlHostname='localhost',
        [string]$MySqlUser='root',
        [string]$MySqlPass
    )
    try {
        # Auf Partitionierung prüfen
        $Path = (Get-MySqlDatadir) + '\greyhound'
        Write-Verbose "GREYHOUND Datenbank-Pfad: $Path" -ErrorAction SilentlyContinue

        if (($Path) -and (Test-Path $Path) -and (!(Get-ChildItem -Path $Path -Filter 'items#*'))) {
            Write-Verbose "GREYHOUND Dienst wird gestoppt..."
            $PrevGreyhoundServerStatus = ((Get-Service GreyhoundService).Status)

            Stop-Service GreyhoundService -ErrorAction Stop
            if (((Get-Service GreyhoundService).Status) -eq 'Stopped') {
                $MySqlQuery =  @'
USE greyhound;
ALTER TABLE items DROP INDEX e_kind, DROP INDEX e_state;
ALTER TABLE items CHANGE e_state e_state TINYINT(1) DEFAULT '1' NOT NULL;
ALTER TABLE items CHANGE e_kind e_kind TINYINT(2) DEFAULT '1' NOT NULL;
ALTER TABLE items DROP PRIMARY KEY, ADD PRIMARY KEY (i_id, e_state, e_kind);
ALTER TABLE items
PARTITION BY LIST(e_state)
SUBPARTITION BY HASH(e_kind)
SUBPARTITIONS 10 (PARTITION isOpen VALUES IN (1), PARTITION isNew VALUES IN (2), PARTITION isQuestion VALUES IN (3), PARTITION isAnswer VALUES IN (4), PARTITION isDone VALUES IN (5), PARTITION isForward VALUES IN (6), PARTITION isDraft VALUES IN (7), PARTITION isRejected VALUES IN (8)
);
'@

                Write-Verbose "Die MySQL-Abfrage wird ausgefuehrt: $MySqlQuery"
                Invoke-MySqlQuery -MySqlQuery $MySqlQuery -MySqlHostname $MySqlHostname -MySqlUser $MySqlUser -MySqlPass $MySqlPass -Verbose
            } else {
                Throw "Der GREYHOUND-Dienst konnte nicht gestoppt werden."
            }

            if ($PrevGreyhoundServerStatus -eq 'Running') {
                Write-Verbose "GREYHOUND Dienst wird gestartet..."
                Start-Service GreyhoundService -ErrorAction Stop
                if (((Get-Service GreyhoundService).Status) -ne 'Running') {
                    Throw "Der GREYHOUND-Dienst konnte nicht gestartet werden."
                }
            }
        } else {
            Write-Host "Die GREYHOUND-Datenbank ist bereits partitioniert. Keine Aktion erforderlich."
        }
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function Get-ApplianceData {
    [CmdletBinding()]
    param (
        [Parameter(
            Mandatory=$true,
            ValueFromPipeline=$true)]
        [string[]]$Serials,
        [Parameter(
            Mandatory=$false)]
        [string]$ApplianceKey
    )

    try {
        $GccUri         = 'https://greyhound-software.com/gcc/jsonrpc/'
        $ContentType    = 'application/json'
    
        $Serials = "`"" + ($Serials -join "`",`"") + "`""
    
        $Body = @"
{
    "jsonrpc": "2.0",
    "method": "GetApplianceData",
    "params": [
        [$Serials],
        "$ApplianceKey"
    ],
    "id": 1
}
"@

        $GccResult = Invoke-WebRequest -Uri $GccUri -Method Post -Body $Body -ContentType $ContentType | ConvertFrom-Json
    
        if ($GccResult.Error) {
            Write-Error $GccResult.Error.Message
        } else {
            $GccResult.Result
        }            
    }
    catch {
        Write-Error $_.Exception.Message
    }
}



function Get-GreyhoundInitialServerData {
    [CmdletBinding()]
    param (
        [Parameter(
            Mandatory=$true,
            ValueFromPipeline=$true)]
        [string]$InstallKey
    )

    try {
        $GccUri         = 'https://greyhound-software.com/gcc/jsonrpc/'
        $ContentType    = 'application/json'
    
        $Body = @"
{
    "jsonrpc": "2.0",
    "method": "GetInitialServerData",
    "params": [
        "$InstallKey"
    ],
    "id": 1
}
"@

        $GccResult = Invoke-WebRequest -Uri $GccUri -Method Post -Body $Body -ContentType $ContentType | ConvertFrom-Json
    
        if ($GccResult.Error) {
            Write-Error $GccResult.Error.Message
        } else {
            $GccResult.Result
        }
            
    }
    catch {
        Write-Error $_.Exception.Message
    }
}