#!/usr/bin/env bash
# remediate-storage-isolation.sh — one-shot, operator-run remediation of an
# existing multi-tenant install (Task 1631). Registers every existing D1
# database and R2 bucket to its owning account, relocates the master token into
# the house-only config file, and strips every account-wide token from every
# sub-account secrets file.
#
# The mapping file is operator-authored JSON: { "<resource-name>": "<accountId>" }.
# The node core fails closed on any enumerated resource the operator did not map;
# ownership is never guessed. This wrapper is a faithful relay: it gates on the
# mapping file existing and on the node exit code, and never echoes a token.
#
# Usage: PLATFORM_ROOT=~/<brand>-code/platform \
#        NEO4J_URI=... NEO4J_PASSWORD=... \
#        remediate-storage-isolation.sh <mapping-file.json>
set -u

log() { echo "[remediate] $*" >&2; }
die() { log "error: $*"; exit 1; }

MAPPING="${1:-}"
[ -n "$MAPPING" ] || die "usage: remediate-storage-isolation.sh <mapping-file.json>"
[ -r "$MAPPING" ] || die "mapping file not readable: '${MAPPING}'"
[ -n "${PLATFORM_ROOT:-}" ] || die "PLATFORM_ROOT not set"

ENTRY="${PLATFORM_ROOT}/lib/storage-broker/dist/bin/remediate-run.js"
[ -f "$ENTRY" ] || die "remediation entry not built: '${ENTRY}' (run the platform build first)"

log "op=remediate mapping=$(basename "$MAPPING") start"
node "$ENTRY" "$MAPPING"
rc=$?
if [ "$rc" -ne 0 ]; then
  log "op=remediate result=failed code=${rc} (no partial write on a fail-closed abort)"
  exit "$rc"
fi
log "op=remediate result=ok"
