#!/usr/bin/env bash
#
# redact.sh — blank out private information in a guide screenshot before it is
# imported to the hub.
#
# Usage:
#   redact.sh <image.png> <WxH+X+Y> [<WxH+X+Y> ...]            solid boxes (default)
#   redact.sh --pixelate <image.png> <WxH+X+Y> [...]           heavy pixelation
#
# Geometry is standard ImageMagick: width x height + x-offset + y-offset,
# e.g. 420x38+180+220. Edits IN PLACE (the pre-redaction original must not
# outlive this step — that's the point).
#
# Why solid boxes by default: light blur over text can be recoverable, and a
# clean box reads as deliberate in client-facing docs. --pixelate uses a
# factor-12 mosaic, acceptable for faces/photos; still prefer boxes for text.
#
# Policy (see the write-guides skill / README "Privacy" section): redaction is
# the SECOND choice. First choice is re-shooting from a source without private
# data (fixture site, or a sample/draft record you create). Never import a
# screenshot to the hub before it has been inspected — the hub media library
# is served publicly and may be CDN-cached; deleting after upload is not a
# reliable undo.

set -euo pipefail

MODE="box"
if [ "${1:-}" = "--pixelate" ]; then
	MODE="pixelate"
	shift
fi

IMG="${1:-}"
shift || true

if [ -z "$IMG" ] || [ "$#" -lt 1 ]; then
	echo "usage: redact.sh [--pixelate] <image.png> <WxH+X+Y> [<WxH+X+Y> ...]" >&2
	exit 1
fi
if [ ! -f "$IMG" ]; then
	echo "redact.sh: no such image: $IMG" >&2
	exit 1
fi

TMP="$(mktemp --suffix=.png)"
trap 'rm -f "$TMP"' EXIT

cp "$IMG" "$TMP"

for GEO in "$@"; do
	if ! [[ "$GEO" =~ ^([0-9]+)x([0-9]+)\+([0-9]+)\+([0-9]+)$ ]]; then
		echo "redact.sh: bad geometry '$GEO' (want WxH+X+Y)" >&2
		exit 1
	fi
	W="${BASH_REMATCH[1]}"; H="${BASH_REMATCH[2]}"; X="${BASH_REMATCH[3]}"; Y="${BASH_REMATCH[4]}"
	if [ "$MODE" = "box" ]; then
		convert "$TMP" -fill '#1d2327' -draw "rectangle $X,$Y $((X+W)),$((Y+H))" "$TMP"
	else
		# Crop the region, mosaic it hard (factor 12), composite it back.
		convert "$TMP" \( +clone -crop "${GEO}" +repage -scale 8.33% -scale "${W}x${H}!" \) \
			-geometry "+${X}+${Y}" -composite "$TMP"
	fi
done

mv "$TMP" "$IMG"
trap - EXIT
chmod 664 "$IMG" 2>/dev/null || true
echo "redacted $# region(s) in $IMG ($MODE)"
