logigate/scripts/restore-backup.mjs

48 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

#!/usr/bin/env node
// Restores data/ from a backup made by server/utils/backup.ts.
//
// node scripts/restore-backup.mjs backups/logigate-2026-10-20.ndjson.gz [target-dir]
//
// The target (default: data) is moved aside to data.before-restore-<time>
// first, so a restore can itself be undone. Stop the container before
// restoring and start it again afterwards.
import { createReadStream, existsSync } from 'node:fs'
import { mkdir, open, rename } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
import { createInterface } from 'node:readline'
import { createGunzip } from 'node:zlib'
const [file, target = 'data'] = process.argv.slice(2)
if (!file) {
console.error('Usage: node scripts/restore-backup.mjs <backup.ndjson.gz> [target-dir]')
process.exit(1)
}
const dir = resolve(target)
if (existsSync(dir)) {
const aside = `${dir}.before-restore-${new Date().toISOString().replace(/[:.]/g, '-')}`
await rename(dir, aside)
console.log(`Moved the current ${target} to ${aside}`)
}
const lines = createInterface({ input: createReadStream(file).pipe(createGunzip()), crlfDelay: Infinity })
let count = 0
let header = null
for await (const line of lines) {
if (!line.trim()) continue
const entry = JSON.parse(line)
if (!header) {
header = entry
if (entry.logigate !== 'backup') throw new Error('Not a Logigate backup')
continue
}
if (typeof entry.path !== 'string' || entry.path.split('/').includes('..')) throw new Error(`Bad path in backup: ${entry.path}`)
const out = join(dir, entry.path)
await mkdir(dirname(out), { recursive: true })
const fh = await open(out, 'w')
await fh.writeFile(entry.data, 'utf8')
await fh.sync()
await fh.close()
count++
}
console.log(`Restored ${count} files from ${file} (made ${header?.created})`)