#!/bin/sh
# Make a new vault code (ADR-007 §1): an age identity, shown once and saved nowhere here.
#
#   tools/new-code NAME [--add]
#
# NAME says which code it is: daily, paper (later: a trusted person).
# --add also appends its recipient (the public half, not secret) to
# recipients/owner.txt. Existing keys/*.age only open with the new code after
# tools/rewrap.
#
# By hand: `age-keygen` prints the same thing; its "public key" line is the recipient.
. "$(dirname "$0")/lib.sh"
need age-keygen
name=; add=no
for a; do case $a in --add) add=yes ;; -*) die "unknown option $a" ;; *) name=$a ;; esac; done
case $name in ''|*[!a-z0-9-]*) die "usage: new-code NAME [--add]   (NAME: daily, paper, ...; a-z 0-9 -)" ;; esac
[ -t 1 ] || say "warning: the code is going to a file or pipe, not to the screen"

code=$(age-keygen 2>/dev/null | grep '^AGE-SECRET-KEY-1') || die "age-keygen failed"
rcp=$(printf '%s\n' "$code" | age-keygen -y) || die "age-keygen -y failed"

printf '\n==== VAULT CODE "%s": save it now (password manager, or the paper kit) ====\n\n' "$name"
printf '    %s\n\n' "$code"
printf 'The same, in groups for paper (spaces do not matter when typing it):\n\n'
printf '    %s\n' "$(printf '%s' "${code#AGE-SECRET-KEY-1}" | sed 's/.\{6\}/& /g; s/ $//; s/^/AGE-SECRET-KEY-1 /')"
printf '\nIts recipient (public, not secret):\n    %s\n' "$rcp"
printf '==== end of code; clear this terminal afterwards (clear; history -c) ====\n\n'
code=

if [ $add = yes ]; then
    mkdir -p "$RECIPIENTS"
    printf '# %s, added %s\n%s\n' "$name" "$(date +%F)" "$rcp" >> "$RECIPIENTS/owner.txt"
    say "added to $RECIPIENTS/owner.txt"
    [ -z "$(ls "$KEYS"/*.pass.age 2>/dev/null)" ] || say "next: tools/rewrap, so the vault opens with this code"
fi
