#!/usr/bin/env bash
# Existing-pi install-log redaction.
#
# Idempotent one-shot remediation for Pis that completed installation BEFORE
# the install-log redaction landed at packages/create-maxy-code/src/index.ts:152.
# Scans every `install-*.log` in the configured logs directory and replaces
# every literal `set-initial-password ...<secret>` payload with
# `set-initial-password [REDACTED]`. Re-running the script is safe —
# already-redacted lines do not match the source pattern, so no further
# edits occur.
#
# Source patterns covered:
#   1. TS installer (packages/create-maxy-code/src/index.ts:152) — "[ISO] > sudo
#      neo4j-admin dbms set-initial-password -- <secret>" or any args after
#      "set-initial-password" (positional or "--" delimited).
#   2. Legacy bash installer (removed) — "+ sudo neo4j-admin dbms
#      set-initial-password <secret>" if bash -x had been on. Pattern kept
#      for historical install logs from before the bash installer's removal.
#
# A trailing marker line `[redact-install-logs] redacted=<n> file=<path>` is
# appended to each modified log so subsequent reads can identify which logs
# went through the remediation. Files with zero matches are left untouched.
#
# Default scan location: $HOME/.maxy/logs (the installer's LOG_DIR). Override
# with --dir <path> for non-default deployments.

set -euo pipefail

LOG_DIR="${HOME}/.maxy/logs"

while [ $# -gt 0 ]; do
  case "$1" in
    --dir) LOG_DIR="$2"; shift 2 ;;
    --help|-h)
      cat <<USAGE
Usage: redact-install-logs.sh [--dir <log-dir>]

Redacts neo4j set-initial-password secrets from install-*.log files.
Default --dir: \$HOME/.maxy/logs

Idempotent — safe to re-run.
USAGE
      exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 2 ;;
  esac
done

if [ ! -d "$LOG_DIR" ]; then
  echo "[redact-install-logs] log dir not found: $LOG_DIR (nothing to do)"
  exit 0
fi

shopt -s nullglob
TOTAL_FILES=0
TOTAL_REDACTIONS=0

for f in "$LOG_DIR"/install-*.log; do
  [ -f "$f" ] || continue
  TOTAL_FILES=$((TOTAL_FILES + 1))

  # Pattern: any "set-initial-password" line followed by one or more args.
  # The replacement keeps the leading prefix (timestamp + cmd up through
  # set-initial-password and an optional "--") and substitutes everything
  # after with [REDACTED]. We anchor the replacement only when the remaining
  # tail is non-empty AND not already "[REDACTED]" — making the script idempotent.
  REDACTED_THIS_FILE=$(
    perl -ne '
      if (/set-initial-password(\s+--)?\s+(\S.*)$/ && $2 ne "[REDACTED]") {
        print STDOUT "1\n";
      }
    ' "$f" | wc -l | tr -d ' '
  )

  if [ "$REDACTED_THIS_FILE" -gt 0 ]; then
    perl -i -pe '
      if (/set-initial-password(\s+--)?\s+(\S.*)$/ && $2 ne "[REDACTED]") {
        s/set-initial-password(\s+--)?\s+\S.*$/set-initial-password${1} [REDACTED]/;
      }
    ' "$f"
    printf "[redact-install-logs] redacted=%d file=%s\n" "$REDACTED_THIS_FILE" "$f" >> "$f"
    echo "[redact-install-logs] redacted=$REDACTED_THIS_FILE file=$f"
    TOTAL_REDACTIONS=$((TOTAL_REDACTIONS + REDACTED_THIS_FILE))
  fi
done

echo "[redact-install-logs] summary files_scanned=$TOTAL_FILES total_redactions=$TOTAL_REDACTIONS"
exit 0
