#!/bin/sh
# Create the encrypted compartments (ADR-001 §1-2). Run once.
#
#   tools/init-vault
#
# Needs: $CONTINUITY_DATA/recipients/owner.txt, one age recipient per line:
# the DAILY and the PAPER code, made with tools/new-code --add (ADR-007 §1).
#
# Prints each compartment's gocryptfs MASTER KEY once. Write them into the
# paper kit (ADR-002 §2). They are not stored anywhere else.
. "$(dirname "$0")/lib.sh"
need age gocryptfs gocryptfs-xray

[ -s "$RECIPIENTS/owner.txt" ] || die "missing $RECIPIENTS/owner.txt: make the codes first (tools/new-code daily --add; tools/new-code paper --add)"
for c in $CONTINUITY_COMPARTMENTS; do
    [ -e "$CIPHER/$c/gocryptfs.conf" ] && die "$c is already initialised; refusing to overwrite it"
done

umask 077
mkdir -p "$CIPHER" "$KEYS" "$MNT"
chmod 700 "$CONTINUITY_DATA"

say "creating compartments: $CONTINUITY_COMPARTMENTS"
printf '\n==== WRITE THESE INTO THE PAPER KIT (gocryptfs master keys) ====\n'
for c in $CONTINUITY_COMPARTMENTS; do
    mkdir -p "$CIPHER/$c" "$MNT/$c"
    pw=$(random_secret)
    printf '%s\n' "$pw" | wrap_to "$RECIPIENTS/owner.txt" "$KEYS/$c.pass.age"
    printf '%s\n' "$pw" | gocryptfs -init -q -passfile /dev/stdin "$CIPHER/$c"
    mk=$(printf '%s\n' "$pw" | gocryptfs-xray -dumpmasterkey "$CIPHER/$c/gocryptfs.conf")
    printf '%s  %s\n' "$c" "$(paper_groups "$mk")"
done
unset pw mk
printf '==== end of master keys; clear this terminal afterwards (clear; history -c) ====\n\n'
say "done. Next: tools/unlock, then add COMPARTMENT.md to each (templates/COMPARTMENT.md)"
