#!/bin/sh
# Write the recovery bundle (charter §9) to a backup disk, next to the
# restic repository and the archives:
#
#   tools/make-bundle DEST_DIR [--bin DIR]
#
# DEST_DIR/recovery-bundle/ then holds: bin/ + VERSIONS.txt (static tools),
# keys/ (age-encrypted unlock files: ciphertext, ADR-002 §1), recipients/,
# docs/ (data format, charter, ADRs), schemas/, templates/, and START-HERE.md
# (from $CONTINUITY_START_HERE). No secrets are written.
. "$(dirname "$0")/lib.sh"
repo_root=$(cd "$(dirname "$0")/.." && pwd)
dest=; bin=
while [ $# -gt 0 ]; do
    case $1 in --bin) bin=$2; shift ;; -*) die "unknown option $1" ;; *) dest=$1 ;; esac
    shift
done
[ -n "$dest" ] || die "usage: make-bundle DEST_DIR [--bin DIR]"
b=$dest/recovery-bundle
mkdir -p "$b"

if [ -n "$bin" ]; then
    mkdir -p "$b/bin"; cp "$bin"/* "$b/bin/"
    [ -f "$bin/../VERSIONS.txt" ] && cp "$bin/../VERSIONS.txt" "$b/"
else
    "$repo_root/tools/fetch-binaries" "$b"
    rm -rf "$b/downloads"
fi
for d in keys recipients; do
    rm -rf "${b:?}/$d"; cp -R "$CONTINUITY_DATA/$d" "$b/$d"
done
rm -rf "$b/docs" "$b/schemas" "$b/templates"
mkdir -p "$b/docs"
cp "$repo_root/docs/data-format.md" "$repo_root/docs/CHARTER.md" "$b/docs/"
cp -R "$repo_root/decisions" "$b/docs/decisions"
cp -R "$repo_root/schemas" "$b/schemas"
cp -R "$repo_root/templates" "$b/templates"
if [ -n "${CONTINUITY_START_HERE:-}" ] && [ -f "$CONTINUITY_START_HERE" ]; then
    cp "$CONTINUITY_START_HERE" "$b/START-HERE.md"
else
    say "WARNING: CONTINUITY_START_HERE is not set; the bundle has no filled-in START-HERE.md"
fi
say "recovery bundle written to $b"
