#!/bin/sh
# Yearly long-term archive (ADR-001 §5): each UNLOCKED compartment as
# tar, piped straight into age. Plaintext never touches disk.
#
#   tools/archive-export DEST_DIR [--recipients FILE] [--no-verify] [c1 c2 ...]
#
# Recipients default to $CONTINUITY_DATA/recipients/archive.txt. age refuses
# to mix post-quantum and classic recipients in one file, so the PQ copy is
# a second run with --recipients recipients/archive-pq.txt (ADR-002 §4).
# Verification decrypts each archive again and lists it (asks for the vault code).
. "$(dirname "$0")/lib.sh"
need age tar sha256sum
dest=; rcp=$RECIPIENTS/archive.txt; verify=yes; list=
while [ $# -gt 0 ]; do
    case $1 in
        --recipients) rcp=$2; shift ;;
        --no-verify) verify=no ;;
        -*) die "unknown option $1" ;;
        *) if [ -z "$dest" ]; then dest=$1; else list="$list $1"; fi ;;
    esac
    shift
done
[ -n "$dest" ] || die "usage: archive-export DEST_DIR [--recipients FILE] [--no-verify] [c1 ...]"
[ -s "$rcp" ] || die "missing recipients file $rcp"
[ $verify = yes ] && need_identity
mkdir -p "$dest"
day=$(date +%F); tag=$(basename "$rcp" .txt); tag=${tag#archive-}   # archive-pq.txt -> .pq
[ "$tag" = archive ] && suffix= || suffix=.$tag

for c in $(compartments $list); do
    is_mounted "$MNT/$c" || die "$c is locked; unlock it first (tools/unlock $c)"
    f=$c-$day$suffix.tar.age
    [ -e "$dest/$f" ] && die "$dest/$f already exists"
    tar --format=pax -C "$MNT/$c" -cf - . | age -R "$rcp" -o "$dest/$f.partial"
    mv "$dest/$f.partial" "$dest/$f"
    (cd "$dest" && sha256sum "$f" > "$f.sha256")
    if [ $verify = yes ]; then
        want=$(cd "$MNT/$c" && find . -type f | wc -l)
        got=$(unwrap "$dest/$f" | tar -tf - | grep -vc '/$' || true)
        [ "$want" -eq "$got" ] || die "$f: archive lists $got files but $c has $want"
        say "$f written and verified ($got files)"
    else
        say "$f written (NOT verified)"
    fi
done
