# install-backup-task.ps1
# Creates a Windows Scheduled Task to run backup-db.ps1 daily at 2:00 AM.
# Must be run as Administrator.

$ErrorActionPreference = 'Stop'

$TaskName   = 'TestDataDB-Backup'
$ScriptPath = 'C:\Shares\testdatadb\backup-db.ps1'

# Check for admin privileges
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host '[ERROR] This script must be run as Administrator.'
    exit 1
}

# Remove existing task if present
$existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
if ($existing) {
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
    Write-Host "[INFO] Removed existing task: $TaskName"
}

# Build task components
$action  = New-ScheduledTaskAction `
    -Execute 'powershell.exe' `
    -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$ScriptPath`""

$trigger = New-ScheduledTaskTrigger -Daily -At '2:00AM'

$settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -StartWhenAvailable `
    -RunOnlyIfNetworkAvailable:$false `
    -ExecutionTimeLimit (New-TimeSpan -Minutes 30)

$taskPrincipal = New-ScheduledTaskPrincipal `
    -UserId 'SYSTEM' `
    -LogonType ServiceAccount `
    -RunLevel Highest

# Register task
Register-ScheduledTask `
    -TaskName $TaskName `
    -Action $action `
    -Trigger $trigger `
    -Settings $settings `
    -Principal $taskPrincipal `
    -Description 'Daily backup of TestDataDB SQLite database with 7-day retention' |
    Out-Null

Write-Host "[OK] Scheduled task '$TaskName' created."
Write-Host "[INFO] Runs daily at 2:00 AM as SYSTEM."
Write-Host "[INFO] Script: $ScriptPath"
