$ErrorActionPreference = 'SilentlyContinue'
$createdNew = $false
$mutex = New-Object Threading.Mutex($true, 'Local\RansomBackupFREE-UserScheduler', [ref]$createdNew)
if (-not $createdNew) { exit 0 }
try {
    Start-Sleep -Seconds 60
    $runCatchUp = $true
    $statusPath = Join-Path $env:LOCALAPPDATA 'RansomBackupFREE\status.json'
    if (Test-Path -LiteralPath $statusPath) {
        try {
            $status = Get-Content -LiteralPath $statusPath -Raw | ConvertFrom-Json
            $lastRun = [DateTimeOffset]::FromUnixTimeSeconds([int64]$status.timestamp)
            $runCatchUp = ([DateTimeOffset]::Now - $lastRun).TotalHours -ge 20
        } catch { $runCatchUp = $true }
    }
    if ($runCatchUp) {
        Start-Process wscript.exe -ArgumentList @("`"$(Join-Path $PSScriptRoot 'LaunchHidden.vbs')`"",'Backup.ps1')
    }
    while ($true) {
        $now = Get-Date
        $next = Get-Date -Hour 18 -Minute 0 -Second 0
        if ($next -le $now) { $next = $next.AddDays(1) }
        $seconds = [math]::Max(60, [int][math]::Ceiling(($next - $now).TotalSeconds))
        Start-Sleep -Seconds $seconds
        Start-Process wscript.exe -ArgumentList @("`"$(Join-Path $PSScriptRoot 'LaunchHidden.vbs')`"",'Backup.ps1')
    }
} finally {
    $mutex.ReleaseMutex()
    $mutex.Dispose()
}
