#!/usr/bin/env bash
set -u

OUT="${1:-$HOME/ndm-production-inventory-$(date +%Y%m%d-%H%M%S).txt}"

exec > >(tee "$OUT") 2>&1

section() {
  printf '\n\n================================================================================\n'
  printf '%s\n' "$1"
  printf '================================================================================\n'
}

redact_stream() {
  sed -E \
    -e 's#(rtsp://[^:/@[:space:]]+):[^@/[:space:]]+@#\1:***@#g' \
    -e 's#(https?://[^:/@[:space:]]+):[^@/[:space:]]+@#\1:***@#g' \
    -e 's#^([[:space:]]*(user|username|pass|password|token|secret|apiKey|api_key|community)[[:space:]]*[:=][[:space:]]*).*$#\1***#Ig'
}

section "NDM PRODUCTION SERVER INVENTORY"
echo "Generated: $(date -Is)"
echo "Hostname: $(hostname)"
echo "Output: $OUT"

section "SYSTEM"
hostnamectl 2>/dev/null || true
uname -a
echo
ip -br addr 2>/dev/null || true
echo
df -h
echo
free -h 2>/dev/null || true
echo
uptime

section "LISTENING PORTS"
ss -lntup 2>/dev/null || true

section "SYSTEMD - RELEVANT SERVICES"
systemctl list-unit-files --type=service 2>/dev/null | \
  grep -Ei 'mediamtx|ndm|stream|record|scheduler|kiosk|clock|temperature|output|shift|planner|nginx' || true

for svc in \
  nginx.service \
  mediamtx.service \
  ndm-auth.service \
  recorder.service \
  scheduler.service \
  ndm-mediamtx-sync.service \
  shift-planner.service
do
  section "SYSTEMD DETAIL: $svc"
  systemctl cat "$svc" 2>/dev/null || true
  echo
  systemctl status "$svc" --no-pager 2>/dev/null || true
done

section "NGINX CONFIGURATION"
if command -v nginx >/dev/null 2>&1; then
  nginx -T 2>&1 | redact_stream || true
else
  grep -Rni . /etc/nginx 2>/dev/null | redact_stream || true
fi

section "REPOSITORY DISCOVERY"
find /opt /srv /var/www -maxdepth 4 -type d -name .git 2>/dev/null | sort || true

for repo in /opt/mediamtx-web /opt/stream-manager /opt/shift-planner; do
  if [ -d "$repo/.git" ]; then
    section "GIT: $repo"
    echo "--- status ---"
    git -C "$repo" status --short 2>&1 || true
    echo
    echo "--- head ---"
    git -C "$repo" log -1 --decorate --oneline 2>&1 || true
    echo
    echo "--- branches ---"
    git -C "$repo" branch -avv 2>&1 || true
    echo
    echo "--- tags ---"
    git -C "$repo" tag --sort=-version:refname 2>&1 | head -100 || true
    echo
    echo "--- remotes ---"
    git -C "$repo" remote -v 2>&1 | redact_stream || true
    echo
    echo "--- top-level files ---"
    find "$repo" -maxdepth 2 -type f -printf '%P\n' 2>/dev/null | sort || true
  fi
done

section "SQLITE DATABASE DISCOVERY"
DBS="$(find /opt /var/lib /srv /var/www -maxdepth 6 -type f \
  \( -name '*.sqlite' -o -name '*.sqlite3' -o -name '*.db' \) 2>/dev/null | sort -u)"
printf '%s\n' "$DBS"

if command -v sqlite3 >/dev/null 2>&1; then
  while IFS= read -r db; do
    [ -n "$db" ] || continue
    [ -f "$db" ] || continue

    section "SQLITE: $db"
    ls -lh "$db" 2>/dev/null || true
    echo
    echo "--- integrity ---"
    sqlite3 "$db" 'PRAGMA integrity_check;' 2>&1 || true
    echo
    echo "--- tables ---"
    sqlite3 "$db" '.tables' 2>&1 || true
    echo
    echo "--- schema ---"
    sqlite3 "$db" '.schema' 2>&1 || true
    echo
    echo "--- row counts ---"
    sqlite3 "$db" "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';" 2>/dev/null |
    while IFS= read -r t; do
      [ -n "$t" ] || continue
      printf '%-40s ' "$t"
      sqlite3 "$db" "SELECT COUNT(*) FROM \"$t\";" 2>/dev/null || echo "?"
    done
  done <<< "$DBS"
else
  echo "sqlite3 command not installed"
fi

section "STREAM MANAGER DOMAIN / AUTH HINTS"
for repo in /opt/mediamtx-web /opt/stream-manager; do
  [ -d "$repo" ] || continue
  grep -RniE \
    'CREATE TABLE|ALTER TABLE|users|persons|roles|groups|permissions|access|sessions|password|devices|device_groups|work_groups' \
    "$repo" \
    --include='*.py' --include='*.sql' --include='*.md' \
    2>/dev/null | head -5000 | redact_stream || true
done

section "SHIFT PLANNER DOMAIN / AUTH HINTS"
if [ -d /opt/shift-planner ]; then
  grep -RniE \
    'CREATE TABLE|ALTER TABLE|persons|users|departments|workplaces|organizational_roles|permissions|sessions|password|work_evidence_mode|timesheets|vacation|employee_workplaces|leader_person_id|module' \
    /opt/shift-planner \
    --include='*.py' --include='*.sql' --include='*.md' \
    2>/dev/null | head -5000 | redact_stream || true
fi

section "MEDIAMTX CONFIGURATION - REDACTED"
for f in \
  /etc/mediamtx.yml \
  /etc/mediamtx.yaml \
  /opt/mediamtx/mediamtx.yml \
  /opt/mediamtx/mediamtx.yaml
do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    redact_stream < "$f"
  fi
done

section "OWNERSHIP / PERMISSIONS"
for p in \
  /opt/mediamtx-web \
  /opt/stream-manager \
  /opt/shift-planner \
  /etc/nginx \
  /etc/mediamtx.yml
do
  [ -e "$p" ] && ls -ld "$p" 2>/dev/null || true
done

section "PYTHON / RUNTIME"
command -v python3 2>/dev/null || true
python3 --version 2>/dev/null || true
echo
command -v sqlite3 2>/dev/null || true
sqlite3 --version 2>/dev/null || true
echo
command -v nginx 2>/dev/null || true
nginx -v 2>&1 || true

section "END"
echo "Finished: $(date -Is)"
echo "Inventory written to: $OUT"
