#!/bin/bash
# Weekly 30-day forget+prune of the owner's pre-wipe workstation repos ctg-backups/workstations/<host> (owner standard 2026-10-30).
# Runs on crystalcave as canutethegreat (key b2-restic-workstations.json, prefix workstations/). Deliberately does NOT touch the
# top-level repos RW-LT09/ and kingscrossstation/ (retired machines' last backups, kept as-is) - they are outside this prefix.
# A repo whose last snapshot ages out is emptied: that is the rule (the pre-wipe copy is a 30-day safety net).
set -uo pipefail
S=/home/canutethegreat/.hermes/scripts/restic-workstations.sh
rc=0
hosts=$(eval "$(python3 -c "import json,os;d=json.load(open(os.path.expanduser('~/.hermes/state/b2-restic-workstations.json')));print('export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s'%(d['applicationKeyId'],d['applicationKey']))")"
  aws --endpoint-url https://s3.us-west-002.backblazeb2.com s3api list-objects-v2 --bucket ctg-backups --prefix workstations/ --delimiter / \
    --query 'CommonPrefixes[].Prefix' --output text | tr '\t' '\n' | cut -d/ -f2 | tr '\n' ' ')
[ -n "$hosts" ] || { echo "no workstation repos found" >&2; exit 1; }
for h in $hosts; do
  echo "== workstations/$h"
  "$S" "$h" unlock >/dev/null 2>&1   # stale locks only (restic refuses to remove live ones)
  "$S" "$h" forget --keep-within 30d --prune || rc=1
done
[ $rc -eq 0 ] && date +%s > "$HOME/.hermes/state/workstations-prune-ok"
exit $rc
