#!/bin/sh
# Create the restic repository for one backup target (ADR-001 §4).
#
#   tools/init-repo TARGET          # e.g. hdd-home, hdd-offsite, object-store
#
# Needs REPO_<target> in the config (dashes as underscores), e.g.
#   REPO_hdd_home=/media/me/HDD-HOME/restic
# Prints the repository password once, for the paper kit.
. "$(dirname "$0")/lib.sh"
need age restic
[ $# -eq 1 ] || die "usage: init-repo TARGET"
t=$1; repo=$(repo_for "$t"); [ -n "$repo" ] || die "REPO_$(printf %s "$t" | tr - _) is not set in $CONTINUITY_CONFIG"
kf=$KEYS/restic-$t.pass.age
[ -e "$kf" ] && die "$kf already exists; refusing to replace the password of an existing repository"
[ -s "$RECIPIENTS/owner.txt" ] || die "missing $RECIPIENTS/owner.txt"

umask 077
# The password IS the dashed paper form, so typing it from paper works as printed.
pw=$(paper_groups "$(random_secret)")
printf '%s\n' "$pw" | wrap_to "$RECIPIENTS/owner.txt" "$kf"
printf '%s\n' "$pw" | restic -r "$repo" --password-file /dev/stdin init -q
printf '\n==== WRITE INTO THE PAPER KIT: restic password for %s ====\n%s\n==== end ====\n\n' "$t" "$pw"
unset pw
say "repository $t created at $repo"
