function LogBooks {
    $source = 'D:\IFSBOData\EquipmentLog'
    $destination = "\\$server\EW\LogBooks"

    if(-not (Test-Path $destination)) { throw "Invalid path $destination" }

    $files = Get-ChildItem -Recurse -File -Path $source

    foreach($file in $files) {

        $split = $file.Name -split '-'
        $eqpNumber = $split[0].Substring(0, 2)
        $eqpType = switch($eqpNumber) {
            '04' { 'RVM' }
            '09' { 'EPID' }
            '11' { 'DC' }
            '13' { 'NTX' }
            '14' { 'VCF' }
            default { 'UNKNOWN' }
        }
        
        $year =  $split[1]
        $month = $split[2]
        $day =   $split[3].Substring(0,2)
        
        $moveTo = "$destination\$eqpType\$year\$month\$day"

        if(-not (Test-Path $moveTo)) { mkdir $moveTo }

        "LogBook: Move $($file.Name) to $moveTo" | Out-File -Append -FilePath $logfile

        Move-Item -Path $file.FullName -Destination $moveTo -Force
    }

}

function EftLogs {
    $source = 'D:\IFSBOData\EFTLog'
    $destination = "\\$server\EW\EFTLogs"

    $files = Get-ChildItem -Recurse -File -Path $source

    foreach($file in $files) {
        
        $split = $file.Name -split '-'
        $year =  $split[2].Substring(0, 4)
        $month = $split[2].Substring(4, 2)
        $day =   $split[2].Substring(6, 2)

        $moveTo = "$destination\$year\$month\$day"

        if(-not (Test-Path $moveTo)) { mkdir $moveTo }

        "EFTLog: Move $($file.Name) to $moveTo" | Out-File -Append -FilePath $logfile

        Move-Item -Path $file.FullName -Destination $moveTo -Force
    }
}

try {
    $logfile = "log.{0}.txt" -f (Get-Date -Format 'yyyy-MM-dd')

    $server = switch -Regex ($env:COMPUTERNAME) {
        'REJ-P' { 'REJ-P-INT003' }
        'REJ-Q' { 'REJ-Q-INT103' }
        'REJ-A' { 'REJ-A-INT201' }
        'REJ-C' { 'REJ-C-INT301' }
        'REJ-E' { 'REJ-E-INT401' } 
        'REJK-D' { 'REJK-D-INT501' }
        default { throw "Unsupported platform" }
    }

    $time = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    "[$time] Start" | Out-File -Append -FilePath $logfile

    LogBooks
    EftLogs

    $time = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    "[$time] Done" | Out-File -Append -FilePath $logfile
}
catch {
    "Error: $_" | Out-File -Append -FilePath $logfile
}
