lore-forge/scripts/restore.sh

72 lines
2.8 KiB
Bash
Executable File

#!/usr/bin/env bash
# Restores a backup that scripts/backup.sh wrote.
#
# scripts/restore.sh <backup>
#
# <backup> is one of its timestamped directories, or its `latest` link. Stop lore-forge and
# loreserver first (systemctl stop loreserver lore-forge). The current database and store are
# moved aside, to lore-forge.sqlite.before-restore-<time> in the data directory and
# <store>.before-restore-<time>, never deleted; remove them once the restore has checked out.
#
# The secret key is not part of a backup. The one in use must be the one that was in use when
# the backup was taken, or lore-forge cannot decrypt its signing keys and will not start.
#
# Everything after the backup is lost: revisions pushed since, accounts, grants, and logins.
# People whose login began or refreshed after the backup sign in again.
#
# Settings, from the environment, as for backup.sh:
#
# LORE_FORGE_DATA_DIR lore-forge's data directory /var/lib/lore-forge
# LORE_STORE loreserver's store /var/lib/loreserver/store
set -euo pipefail
say() { echo "restore: $*" >&2; }
die() { say "$*"; exit 1; }
[ $# -eq 1 ] || die "usage: $0 <backup>"
BACKUP="$(cd "$1" && pwd -P)" || die "no backup at $1"
DATA_DIR="${LORE_FORGE_DATA_DIR:-/var/lib/lore-forge}"
STORE="${LORE_STORE:-/var/lib/loreserver/store}"
DB=lore-forge.sqlite
[ -f "$BACKUP/MANIFEST" ] && [ -f "$BACKUP/$DB" ] && [ -d "$BACKUP/lore-store" ] \
|| die "$BACKUP is not a backup from scripts/backup.sh"
if command -v systemctl >/dev/null 2>&1; then
for unit in lore-forge loreserver; do
! systemctl is-active --quiet "$unit" || die "$unit is running; stop it first: systemctl stop loreserver lore-forge"
done
fi
say "restoring $(sed -n 's/^backup //p' "$BACKUP/MANIFEST")"
sed 's/^/ /' "$BACKUP/MANIFEST" >&2
NOW="$(date -u +%Y%m%dT%H%M%SZ)"
mkdir -p "$DATA_DIR"
if [ -e "$DATA_DIR/$DB" ]; then
mv "$DATA_DIR/$DB" "$DATA_DIR/$DB.before-restore-$NOW"
say "moved the current database to $DATA_DIR/$DB.before-restore-$NOW"
fi
# The write-ahead log belongs to the database it was beside, never to the restored one.
for suffix in -wal -shm; do
[ -e "$DATA_DIR/$DB$suffix" ] && mv "$DATA_DIR/$DB$suffix" "$DATA_DIR/$DB.before-restore-$NOW$suffix"
done
cp -p "$BACKUP/$DB" "$DATA_DIR/$DB.restoring"
mv "$DATA_DIR/$DB.restoring" "$DATA_DIR/$DB"
if [ -e "$STORE" ]; then
mv "$STORE" "$STORE.before-restore-$NOW"
say "moved the current store to $STORE.before-restore-$NOW"
fi
mkdir -p "$(dirname "$STORE")"
cp -Rp "$BACKUP/lore-store" "$STORE.restoring"
mv "$STORE.restoring" "$STORE"
if [ "$(id -u)" = 0 ]; then
# Owned as the services expect, whoever owned the copies.
id lore-forge >/dev/null 2>&1 && chown -R lore-forge:lore-forge "$DATA_DIR/$DB"
id loreserver >/dev/null 2>&1 && chown -R loreserver:loreserver "$STORE"
fi
say "done; start lore-forge, then loreserver: systemctl start lore-forge loreserver"