ninja-one/map-job-archive.ps1

begin {
    # Check for required PowerShell version (7+)
    if (!($PSVersionTable.PSVersion.Major -ge 7)) {
        try {
            # Install PowerShell 7 if missing
            if (!(Test-Path "$env:SystemDrive\Program Files\PowerShell\7")) {
                Write-Output '[INFO] Installing PowerShell version 7...'
                Invoke-Expression "& { $( Invoke-RestMethod https://aka.ms/install-powershell.ps1 ) } -UseMSI -Quiet"
            }
        
            # Refresh PATH
            $env:Path = [System.Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path', 'User')
        
            # Restart script in PowerShell 7
            pwsh -File "`"$PSCommandPath`"" @PSBoundParameters
        
        }
        catch {
            Write-Output '[ERROR] PowerShell 7 was not installed. Update PowerShell and try again.'
            throw $Error
        }
        finally {
            exit $LASTEXITCODE
        }
    }
    else {
        $PSStyle.OutputRendering = 'PlainText'
    }
}
process {
    try {
        if (!(Test-NetConnection -ComputerName jredata01.file.core.windows.net -Port 445).TcpTestSucceeded) {
            Write-Host "[ERROR] Unable to connect to the Azure File Share. ISP is most likely blocking port 445" -ForegroundColor Red
            exit 1
        }
        
        $filePath = "$env:APPDATA\rclone\rclone.conf"

        if (!(Test-Path $filePath)) {
            New-Item -ItemType Directory -Path "$env:APPDATA\rclone" -Force | Out-Null
        }

        $config = Ninja-Property-Get archiverclonereadonly
        Set-Content -Path $filePath -Value $config -Force
    
        $mounts = @(
            @{ Path = "1 - MTP"; Drive = "M" },
            @{ Path = "2 - Clio_Flint"; Drive = "N" },
            @{ Path = "3 - SSM"; Drive = "O" },
            @{ Path = "4 - Solar"; Drive = "P" }
        )
        
        foreach ($mount in $mounts) {
            if (Get-PSDrive -Name $mount.Drive -ErrorAction SilentlyContinue) {
                Write-Host "[INFO] Drive $($mount.Drive): already exists. Skipping mount." -ForegroundColor Yellow
            }
            else {
                Write-Host "[INFO] Mounting $($mount.Path) to $($mount.Drive):" -ForegroundColor Green
                Start-Process rclone -ArgumentList "mount archive:`"$($mount.Path)`" $($mount.Drive): --network-mode --volname `"$($mount.Path)`" --read-only --log-file `"$env:TEMP\JRE-Ninja\rclone.log`" --dir-cache-time 1h --poll-interval 30m --log-level ERROR" -NoNewWindow
            }
        }

        # wait a few seconds to ensure mounts are established
        Start-Sleep -Seconds 5

        # output the last 20 lines of the log file
        $logs = Get-Content -Path "$env:TEMP\JRE-Ninja\rclone.log" -Tail 40 
        $logs | Write-Host

        $now = Get-Date

        foreach ($line in $logs) {
            if ($line -match '^\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}' -and $line -match 'CRITICAL|ERROR|FAILED' -and $line -notmatch 'symlinks not supported without the --links flag') {
                $timestamp = $line.Substring(0, 19)
                $logTime = [datetime]::ParseExact($timestamp, 'yyyy/MM/dd HH:mm:ss', $null)
                if (($now - $logTime).TotalSeconds -le 60) {
                    exit 1
                }
            }
        }
    
        exit 0
    }
    catch {
        # output the error and the line it came from
        Write-Host "[ERROR]: $_"
        Write-Host "Line: $($_.InvocationInfo.ScriptLineNumber)"
        exit 1
    }
}

end {
    
}