#!/bin/bash
# secrets-issuance backup — snapshot the per-client age keys + denylist +
# admin token to /mnt/library so they survive an LXC-105-only failure.
#
# Destination is under /mnt/library/.secrets-issuance-backup/ (dot-prefix to
# stay out of any indexer's path). Mode 0700 root-owned. Privileged LXCs
# that mount /mnt/library would still be able to read it as their root maps
# to host root — accept that trade today; an encrypted-tarball variant
# (separate offline age key) is a follow-up if the LAN trust model changes.
#
# Retention: 14 daily snapshots. Each snapshot is the WHOLE /var/lib/
# secrets-issuance directory (small — ~few KiB per client), so restore is
# just `tar xf <snap> -C /`.

set -euo pipefail

SRC=/var/lib/secrets-issuance
DEST=/mnt/library/.secrets-issuance-backup
RETAIN=14

if [ ! -d "$SRC" ]; then
    echo "[backup] source $SRC missing — nothing to do" >&2
    exit 0
fi
if [ ! -d /mnt/library ]; then
    echo "[backup] /mnt/library not mounted — can't write backup" >&2
    exit 1
fi

install -d -m 0700 "$DEST"
chown root:root "$DEST"

stamp=$(date +%Y%m%d-%H%M%S)
out="$DEST/secrets-issuance-$stamp.tar.gz"

# Include the admin token too (recoverable separately, but trivial size and
# saves a step when restoring after total LXC 105 loss).
tar czf "$out" \
    -C / \
    var/lib/secrets-issuance \
    $([ -f /etc/secrets-issuance/admin-token ] && echo etc/secrets-issuance/admin-token || true)
chmod 0600 "$out"

# Drop oldest beyond retention.
ls -1t "$DEST"/secrets-issuance-*.tar.gz 2>/dev/null \
    | tail -n +$((RETAIN + 1)) \
    | xargs -r rm -f

count=$(ls -1 "$DEST"/secrets-issuance-*.tar.gz 2>/dev/null | wc -l)
size=$(du -sh "$out" | cut -f1)
echo "[backup] wrote $out ($size); kept $count snapshots"
