#!/bin/sh
# Re-encrypt every keys/*.pass.age to the codes in recipients/owner.txt
# (ADR-007, ADR-002 §7). Run it after adding a code (tools/new-code --add)
# or after deleting a lost or leaked code's line from owner.txt.
#
#   tools/rewrap
#
# Asks for a vault code that opens the CURRENT files. Nothing is changed unless
# every file decrypts first. Afterwards refresh the recovery bundles
# (tools/make-bundle) and run a backup.
#
# By hand, per file: age -d -i - F | age -R recipients/owner.txt -o F.new; mv F.new F
. "$(dirname "$0")/lib.sh"
need age
[ -s "$RECIPIENTS/owner.txt" ] || die "missing $RECIPIENTS/owner.txt"
set -- "$KEYS"/*.pass.age
[ -e "$1" ] || die "no keys in $KEYS"
need_identity

for f; do check_code "$f"; done
umask 077
for f; do
    s=$(unwrap "$f") && [ -n "$s" ] || die "could not decrypt $f; nothing more was changed"
    printf '%s\n' "$s" | wrap_to "$RECIPIENTS/owner.txt" "$f.new" || { rm -f "$f.new"; die "could not re-encrypt $f"; }
    mv "$f.new" "$f"
    say "$(basename "$f") now opens with the codes in owner.txt"
done
s=
say "done. Check that each code still opens the vault, then: tools/make-bundle, and a backup"
