import { chmod, unlink } from "node:fs/promises"; import { join } from "node:path"; import { ensureConfigDir, getBackupsDir, getConfigPath } from "./config.ts"; const MAX_BACKUPS = 10; export async function createBackup(): Promise { const configFile = Bun.file(getConfigPath()); if (!(await configFile.exists())) { return null; } await ensureConfigDir(); const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); const backupPath = join(getBackupsDir(), `config-${timestamp}.json`); await Bun.write(backupPath, configFile); await chmod(backupPath, 0o600); await pruneBackups(); return backupPath; } async function pruneBackups(): Promise { const glob = new Bun.Glob("config-*.json"); const entries: string[] = []; for await (const entry of glob.scan({ cwd: getBackupsDir() })) { if (entry.includes("/") || entry.includes("..")) continue; entries.push(entry); } if (entries.length <= MAX_BACKUPS) return; entries.sort(); const toDelete = entries.slice(0, entries.length - MAX_BACKUPS); await Promise.all(toDelete.map((file) => unlink(join(getBackupsDir(), file)))); }