<#
Script: MDL-EFTLog-Archiver.ps1
Emil Holgersen, Thales, 2021-03-19
This script moves EFTLog files to an archive folder structure on the active INT node.
The script is meant to run as a daily scheduled job on the MDL servers, and it has to be run with an account that has "full access" to both the local source folder as well as the destination on INT.
Note that this script was made as a response to the fact that no such feature existed after platform reinstall with version 10.2. I have no idea how this was done in prior versions of the system.
#>

$LogFile = "D:\ifsbosystem\log\EWOPS-MDL-EFTLogArchiver-$(Get-Date -Format 'yyyy-MM-dd').log"
$Source = 'D:\IFSBOData\EFTLog\*'
$Destination = '\\rej-p-int003.rejprod.local\E-Drive\FTP Repository\EW\EFTLogs'

Function Write-Log([String] $LogText,[ValidateSet('INFO','WARN','ERROR','FATAL','DEBUG')][String]$Level='INFO'){
    # Please note that this function requires a $logfile var to be defined, otherwise it will output to pipeline (the standard output, usually the screen)
    If ($LogFile) {
        Add-Content -Path $LogFile -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $Level - $Logtext"
    }
    Else {
        Write-Output "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $Level - $Logtext"
    }

}

Write-Log -LogText "Job start"

$Files = Get-Item -Path $Source | Get-ChildItem -Recurse | Where { $_.Attributes -notcontains 'directory' -and $_.Name -match 'EFTLog-[0-9]{6}-[0-9]{8}.log.gz' }

If(-not $Files) {
    Write-Log -Level WARN -LogText "Job stopping prematurely - No files found"
}
Else {
    Write-Log -LogText "Found $($files.Count) file(s)"
    ForEach($File in $Files) {
        Try {
            $File.name -match 'EFTLog-(?<PKISAM>[0-9]{6})-(?<Year>[0-9]{4})(?<Month>[0-9]{2})(?<Day>[0-9]{2}).log.gz' | Out-Null # this line is to extract the date format as used by bankcardreader (it is incorrect by manufacturer design)
            If (!(Test-Path "$Destination\$($Matches.Year)\$($Matches.Month)\$($Matches.day)\")) {
	            Write-Log -LogText "Creating folder $Destination\$($Matches.Year)\$($Matches.Month)\$($Matches.day)\"
                New-Item -ItemType Directory "$Destination\$($Matches.Year)\$($Matches.Month)\$($Matches.day)\" | Out-Null
            }
            Write-Log -LogText "Moving $($file.Name)"
            $File | Move-Item -Destination "$Destination\$($Matches.Year)\$($Matches.Month)\$($Matches.day)\" -Force -ErrorAction Stop
        }
        Catch {
            Write-Log -Level FATAL -LogText "Failed: $($_.ToString().Trim())" 
        }
    }
}
Write-Log -LogText "Job complete"