#!/bin/bash
# =============================================================================
# The install report
# =============================================================================
#
# Every run writes a timestamped markdown file recording what it installed, what
# it changed, what it left alone, and what it ran as root.
#
# ── Who it is for ──
#
# Not us. It exists so the person who just ran a setup script off the internet
# can hand the result to an agent of THEIR choosing and ask "did this do anything
# it should not have". That is an adversarial read by someone who does not trust
# us, which decides almost every choice below:
#
#   Facts, not narration. "installed docker-ce" is checkable. "set up Docker" is
#   a claim. Every entry names the thing precisely enough to verify against the
#   machine afterwards.
#
#   Recorded by the HELPERS, not by the sections. A section that has to remember
#   to report is a section that will forget, and an incomplete report is worse
#   than none — it reads as a full account. `pkg_install` and `install_config`
#   record themselves, so anything installed or written through them appears
#   whether or not the section author thought about it.
#
#   Kept and skipped are recorded too. "Left your .zshrc alone" is the claim a
#   reviewer most wants substantiated, and it is invisible unless stated.
#
#   NO SECRETS. The whole point is that this file gets shared. Passwords, keys
#   and connection strings are redacted at the moment of recording rather than
#   filtered later — see `report_redact`.
#
# ── Shape ──
#
# Facts accumulate in an array during the run and the file is rendered at the
# end, so a crash halfway leaves no half-written report claiming to be complete.
# `report_flush` is called by the exit trap, which marks it INCOMPLETE and says
# where it stopped.

[[ -n "${OFFICER_REPORT_LOADED:-}" ]] && return 0
OFFICER_REPORT_LOADED=1

REPORT_FACTS=()
REPORT_SECTION="(start)"
REPORT_STARTED="$(date '+%Y-%m-%d %H:%M:%S %Z')"
REPORT_COMPLETE=false

# Where it goes. install.sh exports REPORT_FILE so both halves land in ONE file;
# a half run on its own makes its own.
report_path() {
  if [[ -n "${REPORT_FILE:-}" ]]; then
    echo "$REPORT_FILE"
    return
  fi
  local base="${OFFICER_ROOT:-${USER_HOME:-$HOME}}"
  [[ -d "$base" ]] || base="${USER_HOME:-$HOME}"
  echo "${base}/install-report-$(date '+%Y%m%d-%H%M%S').md"
}

# Redact anything that looks like a credential.
#
# Applied when the fact is RECORDED, not when it is rendered, so a secret never
# sits in memory formatted for printing and cannot be leaked by a future change
# to the renderer. Deliberately blunt: a password that survives is a leak, a URL
# over-redacted is an inconvenience.
report_redact() {
  sed -E \
    -e 's#(://[^:/@[:space:]]+):[^@[:space:]]+@#\1:REDACTED@#g' \
    -e 's#((password|passwd|secret|token|key|apikey|api_key)[[:space:]]*[=:][[:space:]]*)[^[:space:]]+#\1REDACTED#gI'
}

report_section() { REPORT_SECTION="$1"; }

# One fact. `kind` is what a reviewer scans for: installed, kept, changed,
# skipped, ran, started, failed.
report_fact() {
  local kind="$1" text="$2"
  REPORT_FACTS+=("${REPORT_SECTION}|${kind}|$(printf '%s' "$text" | report_redact | tr '\n' ' ')")
}

report_installed() { report_fact installed "$1"; }
report_kept()      { report_fact kept "$1"; }
report_changed()   { report_fact changed "$1"; }
report_skipped()   { report_fact skipped "$1"; }
report_started()   { report_fact started "$1"; }
report_failed()    { report_fact failed "$1"; }

# A command run with privilege. The reviewer's first question is "what did it run
# as root", and the honest answer is a list rather than a promise.
report_ran() { report_fact ran "$1"; }

report_mark_complete() { REPORT_COMPLETE=true; }

# Render. Safe to call twice; the trap and a normal finish both reach it.
report_flush() {
  local dest kinds k
  dest="$(report_path)"
  [[ -n "${REPORT_WRITTEN:-}" ]] && return 0
  REPORT_WRITTEN=1

  {
    echo "# Officer install report"
    echo ""
    if $REPORT_COMPLETE; then
      echo "**Status:** finished."
    else
      echo "**Status: INCOMPLETE — the run stopped during \`${REPORT_SECTION}\`.**"
      echo "Everything below still happened; what comes after it did not."
    fi
    echo ""
    echo "| | |"
    echo "| --- | --- |"
    echo "| started | ${REPORT_STARTED} |"
    echo "| finished | $(date '+%Y-%m-%d %H:%M:%S %Z') |"
    echo "| host | $(hostname 2>/dev/null || echo unknown) |"
    echo "| system | $(uname -srm) |"
    echo "| account | ${USERNAME:-$(id -un)} |"
    echo "| script commit | $(git -C "${SCRIPT_DIR:-.}" rev-parse --short HEAD 2>/dev/null || echo 'not a git checkout') |"
    echo ""
    echo "---"
    echo ""
    echo "## How to review this"
    echo ""
    echo "This file exists so you can hand it to someone — or something — that does"
    echo "not trust the script that wrote it. It is a list of facts, each meant to be"
    echo "checkable against the machine rather than taken on faith."
    echo ""
    echo "Worth asking of it:"
    echo ""
    echo "- Does anything under **installed** come from somewhere other than your"
    echo "  distribution's repositories, Homebrew, or a vendor's documented installer?"
    echo "- Does anything under **changed** touch a file outside this install, your"
    echo "  home directory, or the system configuration a setup script would be"
    echo "  expected to touch?"
    echo "- Does anything under **ran** do more than the section it sits under claims?"
    echo "- Is anything **started** that you did not ask for?"
    echo ""
    echo "Credentials are redacted where they were recorded. If you find one that is"
    echo "not, that is a bug worth reporting — this file is meant to be shareable."
    echo ""
    echo "What this report does NOT cover: anything a package's own post-install"
    echo "script did. Reviewing \`docker-ce\` itself is a different exercise from"
    echo "reviewing the script that installed it."
    echo ""
    echo "---"
    echo ""

    if ((${#REPORT_FACTS[@]} == 0)); then
      echo "_Nothing was recorded — no section made a change._"
    else
      local last=""
      local line section kind text
      for line in "${REPORT_FACTS[@]}"; do
        section="${line%%|*}"
        kind="${line#*|}"; kind="${kind%%|*}"
        text="${line#*|*|}"
        if [[ "$section" != "$last" ]]; then
          [[ -n "$last" ]] && echo ""
          echo "## ${section}"
          echo ""
          last="$section"
        fi
        printf -- '- **%s** — %s\n' "$kind" "$text"
      done
    fi

    echo ""
    echo "---"
    echo ""
    echo "## Summary by kind"
    echo ""
    for k in installed changed kept skipped started ran failed; do
      local n
      n="$(printf '%s\n' "${REPORT_FACTS[@]}" | grep -c "|${k}|" || true)"
      printf -- '- %-10s %s\n' "$k" "$n"
    done
  } >"$dest" 2>/dev/null

  [[ -n "${USERNAME:-}" ]] && chown "${USERNAME}:$(id -gn "$USERNAME" 2>/dev/null || echo "$USERNAME")" "$dest" 2>/dev/null || true
  chmod 0644 "$dest" 2>/dev/null || true

  echo ""
  echo "  Install report: ${dest}"
}
