<#
.SYNOPSIS
    Script for importing a large number of report files into Docusnap

.DESCRIPTION
    The Import-Reports.ps1 PowerShell script manages to prepare docusnap report files (.MRT) for usage in docusnap. It copies files to the user specified Settings-Directory and modifies the existing Repositry XML file with new information.

.PARAMETER
    -Verbose    - Displays additional information on the individual steps of the script.
    -ImportEN   - Imports german reports for usage within EN UI. 
    -Update     - If a report file already exists in the repository XML, both, meta information and MRT-file will be overwritten. Default behavior without this parameter is to skip already existing reports.
    -NoDetect   - Per default the script tries to automatically detect docusnap settings by searching and reading a configuration file. Set this parameter to manually specify parameters required.

.EXAMPLE
    Example of how to use the script:
    PS C:\> .\Import-Reports.ps1

.NOTES
    Company:           Docusnap GmbH
    Version:           2.2.1
    Created on         19.07.2024
    Last Change:       29.01.2025
    Contact:           support@docusnap.com
    Website:           https://docusnap.com
#>
Param([switch]$Verbose=$false, [switch]$ImportEN=$false, [switch]$Update, [switch]$NoDetect)

#region Functions
Function PromptForFolder([String]$mDescription,[String]$mInitialDirectory){
    $mAssemblyFullName = 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    $mAssembly = [System.Reflection.Assembly]::Load($mAssemblyFullName)
    $mOpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $mOpenFileDialog.AddExtension = $mfalse
    $mOpenFileDialog.CheckFileExists = $mfalse
    $mOpenFileDialog.DereferenceLinks = $mtrue
    $mOpenFileDialog.Filter = "Folders|`n"
    $mOpenFileDialog.Multiselect = $mfalse
    $mOpenFileDialog.Title = $mDescription
    $mOpenFileDialog.InitialDirectory = $mInitialDirectory
    $mOpenFileDialogType = $mOpenFileDialog.GetType()
    $mFileDialogInterfaceType = $mAssembly.GetType('System.Windows.Forms.FileDialogNative+IFileDialog')
    $mIFileDialog = $mOpenFileDialogType.GetMethod('CreateVistaDialog',@('NonPublic','Public','Static','Instance')).Invoke($mOpenFileDialog,$mnull)
    $mnull = $mOpenFileDialogType.GetMethod('OnBeforeVistaDialog',@('NonPublic','Public','Static','Instance')).Invoke($mOpenFileDialog,$mIFileDialog)
    [uint32]$mPickFoldersOption = $mAssembly.GetType('System.Windows.Forms.FileDialogNative+FOS').GetField('FOS_PICKFOLDERS').GetValue($mnull)
    $mFolderOptions = $mOpenFileDialogType.GetMethod('get_Options',@('NonPublic','Public','Static','Instance')).Invoke($mOpenFileDialog,$mnull) -bor $mPickFoldersOption
    $mnull = $mFileDialogInterfaceType.GetMethod('SetOptions',@('NonPublic','Public','Static','Instance')).Invoke($mIFileDialog,$mFolderOptions)
    $mVistaDialogEvent = [System.Activator]::CreateInstance($mAssemblyFullName,'System.Windows.Forms.FileDialog+VistaDialogEvents',$mfalse,0,$mnull,$mOpenFileDialog,$mnull,$mnull).Unwrap()
    [uint32]$mAdviceCookie = 0
    $mAdvisoryParameters = @($mVistaDialogEvent,$mAdviceCookie)
    $mAdviseResult = $mFileDialogInterfaceType.GetMethod('Advise',@('NonPublic','Public','Static','Instance')).Invoke($mIFileDialog,$mAdvisoryParameters)
    $mAdviceCookie = $mAdvisoryParameters[1]
    $mResult = $mFileDialogInterfaceType.GetMethod('Show',@('NonPublic','Public','Static','Instance')).Invoke($mIFileDialog,[System.IntPtr]::Zero)
    $mnull = $mFileDialogInterfaceType.GetMethod('Unadvise',@('NonPublic','Public','Static','Instance')).Invoke($mIFileDialog,$mAdviceCookie)
    if ($mResult -eq [System.Windows.Forms.DialogResult]::OK) {
        $mFileDialogInterfaceType.GetMethod('GetResult',@('NonPublic','Public','Static','Instance')).Invoke($mIFileDialog,$mnull)
    }
    return $mOpenFileDialog.FileName
}
Function GetScriptPath(){
    Write-Verbose -Message "Get the current script Path."
    
    Try{
        #for use in PS1
        $mInvocation = (Get-Variable MyInvocation -Scope 1).Value
        $mScriptPath = Split-Path $mInvocation.MyCommand.Path
        if($mScriptPath -eq $null){
            #For ISE debug mode
            $mScriptPath = Split-Path $psISE.CurrentFile.FullPath
        }
        Write-Verbose -Message "Current Script Path is $mScriptPath."
    }Catch{
        #for use in EXE
        $mScriptPath = Split-Path -Parent -Path ([Environment]::GetCommandLineArgs()[0])
        Write-Verbose -Message "Current Script Path is $mScriptPath."
    }finally{
        if($mScriptPath -eq $null){
            Write-Host -ForegroundColor DarkRed "Could not determine the current script path. Error: $($_.Exception.Message)."
        }
    }
    return $mScriptPath
}
Function WriteLog([String]$mFile,[String]$mLogText,[Int32]$mMaxSizeKB = [Int32]100,[Int32]$mMaxHistory = [Int32]5){

    Try
    {
        $mTimeStamp = Get-Date -Format G -ErrorAction:Stop
        $mHistoryTimeStamp = "$(Get-Date -Format "yyyyMMddHHmmss" -ErrorAction:Stop)$($(Get-Date -ErrorAction:Stop).Millisecond)"

        If(!(Test-Path $mFile -ErrorAction:Stop)){
            #Log file does not exist yet
            $mExistingFile = New-Item -ItemType File $mFile -Force -ErrorAction:Stop
            Write-Verbose -Message "Log file $mFile created for the first time."
        }else{
            #Log file already exists - check its size
            $mExistingFile = Get-Item -Path $mFile -ErrorAction:Stop
            if(($mExistingFile.Length / 1024) -gt $mMaxSizeKB){
                #file size exceeded. History management
                Write-Verbose -Message "Log file $mFile size exceeded."
                Try{
                    #generate the name of the respective history file
                    $mHistoryFileName = "$($mExistingFile.BaseName)_$mHistoryTimeStamp$($mExistingFile.Extension)"
                    $mHistoryFile = Rename-Item -Path $mExistingFile.FullName -NewName $mHistoryFileName -ErrorAction:SilentlyContinue
                    Write-Verbose -Message "Exceeded file converted to history file $mHistoryFileName."

                    #delete oldest history files
                    $mAllHistoryFiles = @(Get-ChildItem -Path $mExistingFile.Directory.FullName -ErrorAction:Stop | Where-Object{$_.name -match "$($mExistingFile.BaseName)_\d{14}"} | Sort-Object -Property LastWriteTime -ErrorAction:Stop)
                    if($mAllHistoryFiles.Count -gt $mMaxHistory){
                        #remove old history files
                        $mHistoryFilesToDelete = $mAllHistoryFiles.Count - $mMaxHistory
                        Write-Verbose -Message "$mHistoryFilesToDelete history files to delete..."
                        
                        for($mIndex = 0; $mIndex -le $mHistoryFilesToDelete - 1; $mIndex++){
                            #Write-Verbose -Message "Try to delete history file $($mAllHistoryFiles[$mIndex])"
                            $null = Remove-Item -Path $mAllHistoryFiles[$mIndex] -Force -Confirm:$false -ErrorAction:Stop
                        }
                        Write-Verbose -Message "$mHistoryFilesToDelete history files have been deleted. $mMaxHistory files remaining."
                    }

                    #Create a new, empty file
                    $null = New-Item -ItemType File $mFile -Force -ErrorAction:Stop
                }catch{
                    Write-Host -ForegroundColor DarkRed "Could not manage the file history. Error: $($_.Exception.Message)."
                }
            }
        }
        $null = Add-Content -Path $mFile -Value "$mTimeStamp ; $mLogText" -ErrorAction:Stop -WarningAction:SilentlyContinue
        Write-Verbose -Message "`"$mLogText`" logged to file $mFile."
    }
    Catch
    {
        Write-Host -ForegroundColor Red "Could not write to Log file: $($_.Exception.Message)."
    }
}
Function GetScriptName(){
    Write-Verbose -Message "Get the current script name."
    
    Try{
        #for use in PS1
        $mInvocation = (Get-Variable MyInvocation -Scope 1).Value
        $mScriptName = $mInvocation.MyCommand.Name
        if($mScriptName -eq $null -or $mScriptName.Length -eq 0){
            #For ISE debug mode
            $mScriptName = Split-Path $psISE.CurrentFile.FullPath -Leaf
        }
        Write-Verbose -Message "Current Script name is $mScriptName."
    }Catch{
        Write-Host -ForegroundColor DarkRed "Could not determine the current script name. Error: $($_.Exception.Message)."
        $mScriptName = $null
    }
    Write-Verbose -Message "Current script name is $mScriptName"
    return $mScriptName
}
Function CreateEmptyRepository($mPath){
    Try{
        if(!(Test-Path -Path $mPath)){
            #Create new XML file
            $mContent = '<?xml version="1.0" encoding="utf-8"?>
<DcReportSerializer xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ReportCollection>
    <DcReportData />
  </ReportCollection>
</DcReportSerializer>'
            
            $null = Set-Content -PassThru $mPath -Value $mContent -Force -ErrorAction:Stop
        }else{
            #File exists
            throw "The file $mPath already exists!"
        }
        return $true
    }catch{
        return $false
    }
}
Function AskYesOrNo($mTitle = 'Bitte wählen Sie...', $mText){
    Add-Type -AssemblyName System.Windows.Forms

    $form = New-Object System.Windows.Forms.Form
    $form.Text = $mTitle
    $form.Width = 500
    $form.Height = 200
    $form.StartPosition = "CenterScreen"

    $label = New-Object System.Windows.Forms.Label
    $label.Text = $mText
    $label.AutoSize = $true
    $label.Location = New-Object System.Drawing.Point(50, 50)
    $form.Controls.Add($label)

    $yesButton = New-Object System.Windows.Forms.Button
    $yesButton.Text = "Ja"
    $yesButton.Width = 80
    $yesButton.Location = New-Object System.Drawing.Point(120, 100)
    $yesButton.Add_Click({
        $global:result = $true
        $form.Close()
    })
    $form.Controls.Add($yesButton)

    $noButton = New-Object System.Windows.Forms.Button
    $noButton.Text = "Nein"
    $noButton.Width = 80
    $noButton.Location = New-Object System.Drawing.Point(270, 100)
    $noButton.Add_Click({
        $global:result = $false
        #$form.Close()
    })
    $form.Controls.Add($noButton)

    $form.AcceptButton = $yesButton
    $form.CancelButton = $noButton
    $form.ShowDialog() | Out-Null
    return $global:result
}
Function ImportReports($mSourceRepositoryFile, $mTargetRepositoryFile, $mImportEN=$false, $mUpdateReports, [string]$mReportsAuthor='Docusnap Consulting'){
    Try{
        $mSourceRepositoryFile = Get-Item -Path $mSourceRepositoryFile -Force -ErrorAction:Stop
        $mNewReportFiles = Get-ChildItem -Path $($mSourceRepositoryFile.Directory.FullName) -Recurse -Include '*.mrt'
        $mFileCounter = 0
        $mUpdateAskedOnce = $false

        foreach($mCurrentNewReportFile in $mNewReportFiles){
            $mFileCounter++
            $mStartMessage = "Preparing report file $mFileCounter / $($mNewReportFiles.count) '$($mCurrentNewReportFile.Name)' for import..."
            Write-Host $mStartMessage
            [xml]$mNewReportXML = Get-Content $mCurrentNewReportFile
            Try{
                #Check local repository file
                if(!(Test-Path -Path $mTargetRepositoryFile)){
                    Write-Verbose -Message "Team Settings directory does not contain a repository file. Create default one..."
                    if(&CreateEmptyRepository $mTargetRepositoryFile){
                        Write-Verbose "Report repository created: $mTargetRepositoryFile"
                    }else{
                        throw "Could not create new repository file."
                    }
                }
            
                #Prepare report properties
                if($mCurrentNewReportFile.Name -like 'DE_*' -and $mImportEN){
                    #Convert german reports for usage in EN UI
                    $mCurrentNewReportFileTargetName = $mCurrentNewReportFile.Name.Replace('DE_','EN_')
                    $mCurrentNewReportFileLanguageID = 1 #english 
                }else{
                    #do not modify 
                    $mCurrentNewReportFileTargetName = $mCurrentNewReportFile.Name
                    if($mCurrentNewReportFileTargetName -like 'DE_*'){
                        $mCurrentNewReportFileLanguageID = 0 #german
                    }else{
                        $mCurrentNewReportFileLanguageID = 1 #english
                    }
                }

                #Read Repository files
                [xml]$mTargetRepositoryXML = Get-Content -Path $mTargetRepositoryFile
                [xml]$mSourceRepositoryXML = Get-Content -Path $mSourceRepositoryFile

                #search for existing reports by mrt filename
                $mTargetDCDataNode = $mTargetRepositoryXML.SelectNodes('//DcReportData') | Where-Object{$_.FileName -eq $mCurrentNewReportFileTargetName}
                if($mTargetDCDataNode -ne $null -and -not $mUpdateReports -and -not $mUpdateAskedOnce){
                    #Ask user once for update permission
                    if(&AskYesOrNo -mTitle 'Berichte überschreiben?' -mText 'Bestehende Berichte überschrieben / aktualisieren?'){
                        $mUpdateReports = $true
                    }
                    $mUpdateAskedOnce = $true
                }

                if($mTargetDCDataNode -eq $null -or $mUpdateReports){
                    #Copy node into local repository
                    Write-Verbose -Message "Add report information to local repository file..."
                
                    if($mTargetDCDataNode -ne $null){
                        #previous node exists - remove
                        Write-Verbose "Update of existing reports. The existing configuration for report $($mTargetReportNode.InnerText) will be deleted."
                        $null = $mTargetRepositoryXML.DcReportSerializer.ReportCollection.RemoveChild($mTargetDCDataNode)
                        Write-Verbose -Message "Successfully deleted."
                    }
                    #copy new information into local repository
                    $mNewDCDataNode = $mTargetRepositoryXML.ImportNode(($mSourceRepositoryXML.SelectNodes('//DcReportData') | Where-Object{$_.FileName -eq $mCurrentNewReportFile.Name}),$true)
                    $mNewDCDataNode.Language = $mCurrentNewReportFileLanguageID.ToString()
                    $mNewDCDataNode.FileName = $mCurrentNewReportFileTargetName.ToString()
                    $mNewDCDataNode.Author = $mReportsAuthor
                    $null = $mTargetRepositoryXML.DcReportSerializer.ReportCollection.AppendChild($mNewDCDataNode)
                    $mTargetRepositoryXML.Save($mTargetRepositoryFile)
                    Write-Verbose -Message "Successfully added."

                    #Copy MRT file to settings/reporting directory
                    Write-Verbose -Message "Try to copy report (MRT) file to reporting directory..."
                    $null = Copy-Item -Path $mCurrentNewReportFile.FullName -Destination "$((Get-ChildItem -Path $mTargetRepositoryFile).Directory.FullName)\$mCurrentNewReportFileTargetName" -Force -ErrorAction:Stop
                    Write-Verbose -Message "Import completed for file $($mCurrentNewReportFile.Name)."
                }else{
                    #Already exists - skip
                    Write-Verbose -Message "Entry for report $($mCurrentNewReportFile.Name) already exists in local repository."
                    Write-Verbose -Message "No changes applied for this report. Please use the command line parameter '-Update' to overwrite."
                }
            }catch{
                Write-Verbose -Message "Failed to import report $($mCurrentNewReportFile.Name). Error: $($_.Exception.Message)."
            }            
        }
        return $true
    }catch{
        Write-Verbose -Message "Failed to import reports. Error: $($_.Exception.Message)."
        return $false
    }
   
} 
Function ImportForms($mNewFormsRoot, $mSettingsFolder, $mUpdateForms = $false){
    Try{
        $mFileCounter = 0
        $mUpdateAskedOnce = $false
        if(Test-Path -Path $mNewFormsRoot){
            $mNewFormFiles = Get-ChildItem -Path $mNewFormsRoot -Filter '*.deu' -ErrorAction:Stop
            Foreach($mCurrentNewFormFile in $mNewFormFiles){
                $mFileCounter++
                $mStartMessage = "Preparing input form file $mFileCounter / $($mNewFormFiles.count) '$($mCurrentNewFormFile.Name)' for import..."
                Write-Host $mStartMessage
                $mTargetFormFilePath = "$mSettingsFolder\DataEdit\$($mCurrentNewFormFile.Name)"
                                
                if($(Test-Path -Path $mTargetFormFilePath) -and -not $mUpdateForms -and -not $mUpdateAskedOnce){
                    #Ask user once for update permission
                    if(&AskYesOrNo -mTitle 'Eingabemasken überschreiben?' -mText 'Bestehende Eingabemasken überschrieben?'){
                        $mUpdateForms = $true
                    }
                    $mUpdateAskedOnce = $true
                }
                            
                if(!$(Test-Path -Path $mTargetFormFilePath) -or $mUpdateForms){
                    #not existing or update
                    $null = Copy-Item -Path $mCurrentNewFormFile.FullName -Destination $mTargetFormFilePath -Force -ErrorAction:Stop
                    Write-Verbose -Message "Input form file $($mCurrentNewFormFile.Name) imported."
                }else{
                    Write-Verbose -Message "Skipping file $($mCurrentNewFormFile.Name) as it already exists in $mSettingsFolder`\DataEdit."
                }
            }
            return $true
        }else{
            Write-Verbose "No forms found to import."
            return $true
        }
    }catch{
        Write-Error "Failed to import input forms. Error: $($_.Exception.Message)."
        return $false
    }
}
Function DC_GetDSInstallPath(){
    #Find the latest Docusnap install directory based on DocusnapServer.exe
    $mDSServices = Get-WmiObject -Class Win32_Service -Filter "Name LIKE 'Docusnap%Server'" -ErrorAction:Stop
    Foreach($mCurrentDSService in $mDSServices){
        $mCurrentDSServiceFilePath = $mCurrentDSService.PathName.Replace('"','')
        if(Test-Path -Path $mCurrentDSServiceFilePath){
            $mCurrentDSServiceFile = Get-Item -Path $mCurrentDSServiceFilePath -ErrorAction:Stop
            if(($mLatestVersionFile -eq $null) -or ($mLatestVersionFile.VersionInfo.ProductVersion -le $mCurrentDSServiceFile.VersionInfo.ProductVersion)){
                #This is the latest version found yet
                $mLatestVersionFile = $mCurrentDSServiceFile
            }
        }
    }
    if($mLatestVersionFile -ne $null){
        Write-Verbose "Docusnap installation found in directory: $($mLatestVersionFile.Directory.FullName)"
        return $mLatestVersionFile.Directory.FullName
    }else{
        #user defined paths
        $mInstallDir = &PromptForFolder 'Please select the Docusnap program installation directory' "$($env:ProgramFiles)\Docusnap 13"
        Write-Verbose "User specified installation directory: $mInstallDir"
        return $mInstallDir
    }
}
Function DC_GetDSSSettingsPath($mDSInstallPath){
    try {
        #Check Docusnap major version
        if(($mDSInstallPath -eq $null -or $mDSInstallPath.lenth -eq 0) -or -not $(Test-Path -Path $mDSInstallPath)){
            $mDSInstallPath = &DC_GetDSInstallPath
        }
        
        if($mDSInstallPath -match '\d+$'){
            $mVersion = $Matches[0]
        }

        if($mVersion -ge 14){
            #try to extract info from new configuration file
            Write-Verbose "Docusnap version 14 or higher detected."
            # Search configuration in DocusnapSettings.xml
            $mDSettingsFile = [xml](Get-Content 'c:\ProgramData\Docusnap\DocusnapSettings.xml' -ErrorAction:Stop)
            $mDConfigFilePath = $mDSettingsFile.SelectSingleNode('//AlternativeConfigFile').InnerText
            if($mDConfigFilePath -eq $null -or $mDConfigFilePath.length -eq 0 -or -not (Test-Path $mDConfigFilePath)){
                #Search in user profile
                Write-Verbose "Configuration file not found via DocusnapSettings.xml"
                $mDConfigFilePath = "$($env:APPDATA)\Docusnap\Configuration.xml"
                if(-not (Test-Path -Path $mDConfigFilePath)){            
                    #Ask for Docusnap Configuration file
                    Write-Verbose "Configuraton file not found in user profile. Prompt for user input."
                    $null = Add-Type -AssemblyName System.Windows.Forms -ErrorAction:Stop
                    $mOpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
                    $mOpenFileDialog.Title = "Bitte wählen Sie die Docusnap Konfigurations-Datei (z.B. Configuration.xml) aus."
                    $mOpenFileDialog.Filter = "Docusnap Konfiguration (*.xml)|*.xml"
                    if ($mOpenFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
                        # Zeige den ausgewählten Pfad
                        $mDConfigFilePath = $($mOpenFileDialog.FileName)
                    }else{
                        throw "Die Docunsap Konfigurations-Datei, welche benötigte Parameter beinhaltet, konnte nicht gefunden werden!"
                    }

                    if($mDConfigFilePath -eq $null -or $mDConfigFilePath.Length -eq 0 -or -not (Test-Path $mDConfigFilePath)){
                        throw "Configuration file not found."
                    }
                }
            }
            #Extract information
            Write-Verbose "Try to extract information from configuration file $mDConfigFilePath"
            $mConfiguration = [xml](Get-Content $mDConfigFilePath)
            $mTeamsSettings = $mConfiguration.DcConfig._sNetworkSettingsPath
            $mLocalSettings = $mConfiguration.DcConfig._sLocalSettingsPath
            if($mTeamsSettings -ne $null -and $mTeamsSettings.length -gt 0 -and (Test-Path $mTeamsSettings)){
                Write-Verbose "Teams settings path $mTeamsSettings found in configuration file $mDConfigFilePath"
                return $mTeamsSettings
            }elseif($mLocalSettings -ne $null -and $mLocalSettings.length -gt 0 -and (Test-Path $mLocalSettings)){
                Write-Verbose "Local settings path $mTeamsSettings found in configuration file $mDConfigFilePath"
                return $mLocalSettings
            }else{
                throw "Neither team- nor local settings path was found in configuration file $mDConfigFilePath."
            }
        }else{
            Write-Verbose "Docusnap version 13 or prior detected. Unable to auto-detect settings."
            throw "Cannot detect system paths."
        }
    }catch{
        Write-Verbose "Ask user for settings path due to: $($_.Exception.Message)."
        return &PromptForFolder 'Bitte geben Sie den Verzeichnispfad der "Teams-Einstellungen" an.' 'C:\Docusnap'
    }
}
        
#endregion
#region Variables
if($Verbose){$VerbosePreference = 'Continue'}else{$VerbosePreference = 'SilentlyContinue'}

$ScriptPath = &GetScriptPath
$ScriptName = &GetScriptName    

#Log Folder
if($Settings.LogFolder -eq $null -or $Settings.LogFolder.Length -eq 0){
    $LogFile = "$ScriptPath\$($ScriptName.replace('.ps1','.log'))"
}else{
    $LogFile = "$($Settings.LogFolder)\$($ScriptName.replace('.ps1','.log'))"
}
#endregion

Try{
    #Docusnap Installationsverzeichnis ermitteln und prüfen
    $InstallDirectory = &DC_GetDSInstallPath
    if($InstallDirectory -eq $null -or $InstallDirectory.Length -eq 0 -or !(Test-Path -Path $InstallDirectory)){
        throw "Could not determine the docusnap installation directory."
    }

    #Docusnap Teams-Einstellungen Verzeichnis ermitteln und prüfen
    If(-not $NoDetect){
        $TeamSettingsPath = &DC_GetDSSSettingsPath -mDSInstallPath $InstallDirectory
    }else{
        $TeamSettingsPath = &PromptForFolder 'Bitte geben Sie den Verzeichnispfad der "Teams-Einstellungen" an.' 'C:\Docusnap'
    }

    if($TeamSettingsPath -eq $null -or $TeamSettingsPath.Length -eq 0 -or !(Test-Path -Path $TeamSettingsPath)){
        throw "Could not determine the docusnap settings directory."    
    }

    #Pfade für die Repository-Dateien festlegen
    $TargetReportRepositoryFile = "$TeamSettingsPath\Reporting\ReportRepository.xml"
    Write-Verbose "Target repository file path: $TargetReportRepositoryFile"
    $SourceReportRepositoryFile = "$ScriptPath\Reporting\ReportRepository.xml"
    Write-Verbose "Source repository file path: $SourceReportRepositoryFile"

    #Import report files
    if(&ImportReports -mSourceRepositoryFile $SourceReportRepositoryFile -mTargetRepositoryFile $TargetReportRepositoryFile -mImportEN $ImportEN -mUpdateReports $Update){
        $MessageText = 'Import reports: Success'
        &WriteLog $LogFile $MessageText
        Write-Host -ForegroundColor Green $MessageText

        #Import user interfaces
        if(&ImportForms -mNewFormsRoot "$ScriptPath\DataEdit" -mSettingsFolder $TeamSettingsPath -mUpdateForms $Update){
            $MessageText = 'Import input forms: Success'
            &WriteLog $LogFile $MessageText
            Write-Host -ForegroundColor Green $MessageText
        }else{
            throw "Failed to import input forms."
        }
    }else{
        throw "Failed to import reports."
    }
}catch{
    $MessageText = $($_.Exception.Message)
    Write-Host -ForegroundColor Red "$MessageText"
    &WriteLog $LogFile $MessageText
}