Files
roa2web-service-auto/deployment/windows/scripts/Setup-DailyBackup.ps1
Marius Mutu 6b13ffa183 Initial commit: ROA2WEB - FastAPI + Vue.js + Telegram Bot
Modern ERP Reports Application with microservices architecture

Tech Stack:
- Backend: FastAPI + python-oracledb (Oracle DB integration)
- Frontend: Vue.js 3 + PrimeVue + Vite
- Telegram Bot: python-telegram-bot + SQLite
- Infrastructure: Shared database pool, JWT authentication, SSH tunnel

Features:
- FastAPI backend with async Oracle connection pool
- Vue.js 3 responsive frontend with PrimeVue components
- Telegram bot alternative interface
- Microservices architecture with shared components
- Complete deployment support (Linux Docker + Windows IIS)
- Comprehensive testing (Playwright E2E + pytest)

Repository Structure:
- reports-app/ - Main application (backend, frontend, telegram-bot)
- shared/ - Shared components (database pool, auth, utils)
- deployment/ - Deployment scripts (Linux & Windows)
- docs/ - Project documentation
- security/ - Security scanning and git hooks
2025-10-25 14:55:08 +03:00

366 lines
12 KiB
PowerShell

<#
.SYNOPSIS
Setup Daily Backup Task for ROA2WEB Telegram Bot Database
.DESCRIPTION
This script configures Windows Task Scheduler to run daily database backups:
- Creates scheduled task (ROA2WEB-TelegramBot-Backup)
- Runs daily at specified time (default: 2:00 AM)
- Executes Backup-TelegramDB.ps1 script
- Runs as SYSTEM account
- Logs all backup operations
- Optional email notifications on failure
.PARAMETER BackupTime
Daily backup time in 24-hour format (default: "02:00")
.PARAMETER TaskName
Name of the scheduled task (default: ROA2WEB-TelegramBot-Backup)
.PARAMETER InstallPath
Installation path (default: C:\inetpub\wwwroot\roa2web\telegram-bot)
.PARAMETER RunAsUser
User account to run task (default: SYSTEM)
.PARAMETER EnableEmailAlerts
Enable email notifications on backup failure (default: false)
.EXAMPLE
.\Setup-DailyBackup.ps1
Setup daily backup at 2:00 AM
.EXAMPLE
.\Setup-DailyBackup.ps1 -BackupTime "03:30"
Setup daily backup at 3:30 AM
.EXAMPLE
.\Setup-DailyBackup.ps1 -EnableEmailAlerts $true
Setup with email notifications on failure
.NOTES
Author: ROA2WEB Team
Requires: PowerShell 5.1+, Administrator privileges
#>
[CmdletBinding()]
param(
[string]$BackupTime = "02:00",
[string]$TaskName = "ROA2WEB-TelegramBot-Backup",
[string]$InstallPath = "C:\inetpub\wwwroot\roa2web\telegram-bot",
[string]$RunAsUser = "SYSTEM",
[bool]$EnableEmailAlerts = $false
)
$ErrorActionPreference = "Stop"
# =============================================================================
# HELPER FUNCTIONS
# =============================================================================
function Write-Step {
param([string]$Message)
Write-Host "`n[*] $Message" -ForegroundColor Cyan
}
function Write-Success {
param([string]$Message)
Write-Host " [OK] $Message" -ForegroundColor Green
}
function Write-Error {
param([string]$Message)
Write-Host " [ERROR] $Message" -ForegroundColor Red
}
function Write-Warning {
param([string]$Message)
Write-Host " [WARN] $Message" -ForegroundColor Yellow
}
function Test-Administrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]$identity
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Test-BackupScript {
$backupScriptPath = Join-Path $PSScriptRoot "Backup-TelegramDB.ps1"
if (-not (Test-Path $backupScriptPath)) {
throw "Backup script not found: $backupScriptPath"
}
Write-Success "Backup script found: $backupScriptPath"
return $backupScriptPath
}
function Remove-ExistingTask {
param([string]$TaskName)
Write-Step "Checking for existing scheduled task..."
try {
$existingTask = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
if ($existingTask) {
Write-Warning "Existing task found, removing..."
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
Write-Success "Existing task removed"
} else {
Write-Success "No existing task found"
}
} catch {
Write-Warning "Could not check for existing task: $_"
}
}
function New-ScheduledBackupTask {
param(
[string]$TaskName,
[string]$BackupScriptPath,
[string]$BackupTime,
[string]$RunAsUser
)
Write-Step "Creating scheduled task..."
try {
# Parse backup time
$timeComponents = $BackupTime -split ":"
$hour = [int]$timeComponents[0]
$minute = [int]$timeComponents[1]
# Create task action (run PowerShell script)
$action = New-ScheduledTaskAction `
-Execute "PowerShell.exe" `
-Argument "-NoProfile -ExecutionPolicy Bypass -File `"$BackupScriptPath`""
# Create task trigger (daily at specified time)
$trigger = New-ScheduledTaskTrigger `
-Daily `
-At (Get-Date).Date.AddHours($hour).AddMinutes($minute)
# Create task settings
$settings = New-ScheduledTaskSettings `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-StartWhenAvailable `
-RunOnlyIfNetworkAvailable:$false `
-ExecutionTimeLimit (New-TimeSpan -Hours 2)
# Create task principal (run as specified user)
if ($RunAsUser -eq "SYSTEM") {
$principal = New-ScheduledTaskPrincipal `
-UserId "SYSTEM" `
-LogonType ServiceAccount `
-RunLevel Highest
} else {
$principal = New-ScheduledTaskPrincipal `
-UserId $RunAsUser `
-LogonType Password `
-RunLevel Highest
}
# Register task
$task = Register-ScheduledTask `
-TaskName $TaskName `
-Action $action `
-Trigger $trigger `
-Settings $settings `
-Principal $principal `
-Description "Daily backup of ROA2WEB Telegram Bot SQLite database"
Write-Success "Scheduled task created: $TaskName"
Write-Success "Schedule: Daily at $BackupTime"
Write-Success "Run as: $RunAsUser"
return $task
} catch {
throw "Failed to create scheduled task: $_"
}
}
function Test-TaskCreation {
param([string]$TaskName)
Write-Step "Verifying task creation..."
try {
$task = Get-ScheduledTask -TaskName $TaskName -ErrorAction Stop
$taskInfo = Get-ScheduledTaskInfo -TaskName $TaskName
Write-Success "Task verified: $TaskName"
Write-Host " Task State: $($task.State)" -ForegroundColor Gray
Write-Host " Last Run: $($taskInfo.LastRunTime)" -ForegroundColor Gray
Write-Host " Last Result: $($taskInfo.LastTaskResult)" -ForegroundColor Gray
Write-Host " Next Run: $($taskInfo.NextRunTime)" -ForegroundColor Gray
return $true
} catch {
Write-Error "Task verification failed: $_"
return $false
}
}
function Test-TaskExecution {
param([string]$TaskName)
Write-Step "Testing task execution..."
try {
# Run task immediately
Start-ScheduledTask -TaskName $TaskName
Write-Success "Task execution started"
Write-Host " Waiting for task to complete..." -ForegroundColor Yellow
# Wait for task to complete (max 60 seconds)
$timeout = 60
$elapsed = 0
while ($elapsed -lt $timeout) {
Start-Sleep -Seconds 2
$elapsed += 2
$taskInfo = Get-ScheduledTaskInfo -TaskName $TaskName
$task = Get-ScheduledTask -TaskName $TaskName
if ($task.State -ne "Running") {
break
}
Write-Host " Task still running... ($elapsed/$timeout seconds)" -ForegroundColor Yellow
}
# Check result
$taskInfo = Get-ScheduledTaskInfo -TaskName $TaskName
if ($taskInfo.LastTaskResult -eq 0) {
Write-Success "Task executed successfully"
Write-Success "Last run: $($taskInfo.LastRunTime)"
return $true
} else {
Write-Warning "Task completed with result code: $($taskInfo.LastTaskResult)"
Write-Host " Check backup logs for details" -ForegroundColor Yellow
return $false
}
} catch {
Write-Error "Task execution test failed: $_"
return $false
}
}
function Show-TaskSummary {
param([string]$TaskName, [string]$BackupTime, [string]$InstallPath)
Write-Host "`n" + ("=" * 80) -ForegroundColor Cyan
Write-Host " DAILY BACKUP TASK CONFIGURED SUCCESSFULLY" -ForegroundColor Green
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host "`nTask Configuration:" -ForegroundColor Yellow
Write-Host " Task Name: $TaskName"
Write-Host " Schedule: Daily at $BackupTime"
Write-Host " Run As: $RunAsUser"
Write-Host " Installation Path: $InstallPath"
$task = Get-ScheduledTask -TaskName $TaskName
$taskInfo = Get-ScheduledTaskInfo -TaskName $TaskName
Write-Host "`nTask Status:" -ForegroundColor Yellow
Write-Host " State: $($task.State)"
Write-Host " Last Run: $($taskInfo.LastRunTime)"
Write-Host " Last Result: $($taskInfo.LastTaskResult)"
Write-Host " Next Run: $($taskInfo.NextRunTime)"
Write-Host "`nManagement Commands:" -ForegroundColor Yellow
Write-Host " View task: Get-ScheduledTask -TaskName '$TaskName'"
Write-Host " Run manually: Start-ScheduledTask -TaskName '$TaskName'"
Write-Host " Disable task: Disable-ScheduledTask -TaskName '$TaskName'"
Write-Host " Enable task: Enable-ScheduledTask -TaskName '$TaskName'"
Write-Host " Remove task: Unregister-ScheduledTask -TaskName '$TaskName'"
Write-Host "`nBackup Management:" -ForegroundColor Yellow
Write-Host " Manual backup: .\Backup-TelegramDB.ps1"
Write-Host " Backup logs: Get-Content $InstallPath\logs\backup.log -Tail 50"
Write-Host " Backups location: $InstallPath\backups"
Write-Host "`n" + ("=" * 80) -ForegroundColor Cyan
}
# =============================================================================
# MAIN SETUP FLOW
# =============================================================================
function Main {
Write-Host @"
====================================================================
ROA2WEB Telegram Bot - Setup Daily Backup Task
Configure automated database backup via Task Scheduler
====================================================================
"@ -ForegroundColor Cyan
# Check prerequisites
Write-Step "Checking prerequisites..."
if (-not (Test-Administrator)) {
Write-Error "This script must be run as Administrator"
Write-Host " Right-click PowerShell and select 'Run as Administrator'" -ForegroundColor Yellow
exit 1
}
Write-Success "Running as Administrator"
# Find backup script
$backupScriptPath = Test-BackupScript
# Validate installation path
if (-not (Test-Path $InstallPath)) {
Write-Error "Installation path not found: $InstallPath"
Write-Host " Run Install-TelegramBot.ps1 first" -ForegroundColor Yellow
exit 1
}
Write-Success "Installation path verified"
try {
# Setup task
Remove-ExistingTask -TaskName $TaskName
$task = New-ScheduledBackupTask `
-TaskName $TaskName `
-BackupScriptPath $backupScriptPath `
-BackupTime $BackupTime `
-RunAsUser $RunAsUser
# Verify task creation
$verified = Test-TaskCreation -TaskName $TaskName
if ($verified) {
# Test task execution
Write-Host "`nDo you want to test the backup task now? (Y/N)" -ForegroundColor Yellow
$response = Read-Host
if ($response -eq "Y" -or $response -eq "y") {
Test-TaskExecution -TaskName $TaskName
} else {
Write-Host " Skipping test execution" -ForegroundColor Gray
}
# Show summary
Show-TaskSummary -TaskName $TaskName -BackupTime $BackupTime -InstallPath $InstallPath
Write-Host "`nSetup completed successfully!" -ForegroundColor Green
exit 0
} else {
throw "Task verification failed"
}
} catch {
Write-Host "`n[SETUP FAILED] $_" -ForegroundColor Red
Write-Host $_.ScriptStackTrace -ForegroundColor Red
exit 1
}
}
# Run main setup
Main