import { mkdir, rm } from "node:fs/promises"; import path from "node:path"; import { spawnSync } from "node:child_process"; import { backupPostgresDatabase, pruneBackups, scheduledBackupName, verifyPostgresBackup, } from "./database-backup.mjs"; const root = process.env.DEPLOY_ROOT; if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute"); process.loadEnvFile(path.join(root, "shared/.env.production")); const container = process.env.POSTGRES_CONTAINER; if (!container || !/^[a-zA-Z0-9_.-]+$/.test(container)) { throw new Error("POSTGRES_CONTAINER is required"); } const retentionDays = Number(process.env.BACKUP_RETENTION_DAYS ?? "14"); if (!Number.isInteger(retentionDays) || retentionDays < 1) { throw new Error("BACKUP_RETENTION_DAYS must be a positive integer"); } const directory = path.join(root, "shared/backups"); await mkdir(directory, { recursive: true }); const destination = path.join(directory, scheduledBackupName()); await backupPostgresDatabase({ container, destination }); try { await verifyPostgresBackup({ container, file: destination }); } catch (error) { await rm(destination, { force: true }); throw error; } await pruneBackups(directory, { retentionDays }); const offsiteTarget = process.env.BACKUP_OFFSITE_TARGET?.trim(); if (offsiteTarget) { if ( !/^[a-zA-Z0-9_.@:/-]+$/.test(offsiteTarget) || offsiteTarget.startsWith("-") || offsiteTarget.includes("..") ) { throw new Error("BACKUP_OFFSITE_TARGET contains unsupported characters"); } const result = spawnSync("rsync", ["-a", "--partial", destination, offsiteTarget], { stdio: "inherit", env: process.env, }); if (result.status !== 0) throw new Error("Offsite backup copy failed"); } console.log(`scheduled backup written: ${destination}`);