#!/bin/sh
# Back up the CIPHERTEXT (cipher/, keys/, recipients/) to one restic target,
# then check the repository (ADR-001 §4). Never backs up plaintext.
#
#   tools/backup TARGET [--allow-mounted]
#
# A backup only counts after a successful restore test (charter §9):
# run tools/restore-test afterwards.
#
# Unattended runs on the server (object-store target) can read the restic
# password from PASSFILE_<target> (a 0600 file) instead of decrypting it.
# That password only opens gocryptfs ciphertext the server already holds,
# so it exposes nothing new; use an append-only / object-lock bucket so a
# compromised server cannot delete old snapshots.
. "$(dirname "$0")/lib.sh"
need restic
t=; allow=no
for a; do case $a in --allow-mounted) allow=yes ;; -*) die "unknown option $a" ;; *) t=$a ;; esac; done
[ -n "$t" ] || die "usage: backup TARGET [--allow-mounted]"
repo=$(repo_for "$t"); [ -n "$repo" ] || die "REPO_$(printf %s "$t" | tr - _) is not set"
if any_mounted && [ $allow = no ]; then
    die "compartments are unlocked; lock them first (tools/lock) so the backup is consistent, or pass --allow-mounted"
fi

pf=$(eval "printf '%s' \"\${PASSFILE_$(printf %s "$t" | tr - _):-}\"")
if [ -n "$pf" ]; then
    pw=$(cat "$pf") || die "cannot read $pf"
else
    need age; need_identity
    pw=$(unwrap "$KEYS/restic-$t.pass.age") || die "cannot decrypt the restic password for $t"
fi
cd "$CONTINUITY_DATA"   # paths are stored relative: restores land in <target>/cipher/...
printf '%s\n' "$pw" | restic -r "$repo" --password-file /dev/stdin backup --tag continuity -q cipher keys recipients
printf '%s\n' "$pw" | restic -r "$repo" --password-file /dev/stdin check -q
unset pw
say "backup to $t done and repository checked. Not yet proven: run tools/restore-test $t"
