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

OUT_BASE="${1:-$HOME}"
TS="$(date +%Y%m%d-%H%M%S)"
OUT="$OUT_BASE/stream-manager-inventory-$TS"
mkdir -p "$OUT"

find_repo() {
  for p in /opt/mediamtx-web /opt/stream-manager /srv/stream-manager /var/www/stream-manager; do
    if [ -d "$p/.git" ]; then
      printf '%s\n' "$p"
      return 0
    fi
  done
  return 1
}

REPO="${STREAM_MANAGER_REPO:-$(find_repo 2>/dev/null || true)}"

{
  echo "=== SYSTEM ==="
  date -Is
  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
} > "$OUT/system.txt" 2>&1

if [ -n "${REPO:-}" ] && [ -d "$REPO/.git" ]; then
  {
    git -C "$REPO" status --short 2>&1 || true
    echo
    git -C "$REPO" log -1 --decorate --oneline 2>&1 || true
    echo
    git -C "$REPO" branch -avv 2>&1 || true
    echo
    git -C "$REPO" tag --sort=-version:refname | head -50 2>&1 || true
    echo
    git -C "$REPO" remote -v 2>&1 || true
  } > "$OUT/git.txt"

  git -C "$REPO" bundle create "$OUT/repository.bundle" --all >"$OUT/git-bundle.log" 2>&1 || true

  find "$REPO" -maxdepth 4 -type f     \( -name "*.py" -o -name "*.html" -o -name "*.js" -o -name "*.css" -o -name "*.sql" -o -name "*.md" -o -name "*.service" \)     -printf '%P\n' 2>/dev/null | sort > "$OUT/source-files.txt"
fi

{
  systemctl list-unit-files --type=service 2>/dev/null | grep -Ei 'mediamtx|ndm|record|scheduler|kiosk|clock|temperature|output|stream' || true
  echo
  for svc in mediamtx.service ndm-auth.service recorder.service scheduler.service ndm-mediamtx-sync.service; do
    echo "=== $svc ==="
    systemctl cat "$svc" 2>/dev/null || true
    systemctl status "$svc" --no-pager 2>/dev/null || true
    echo
  done
} > "$OUT/services.txt" 2>&1

grep -RniE 'mediamtx|stream|record|auth|8888|8889|9997' /etc/nginx 2>/dev/null > "$OUT/nginx.txt" || true

{
  for f in /etc/mediamtx.yml /etc/mediamtx.yaml /opt/mediamtx/mediamtx.yml /opt/mediamtx/mediamtx.yaml; do
    [ -f "$f" ] || continue
    echo "=== $f ==="
    sed -E       -e 's#(rtsp://[^:/@[:space:]]+):[^@/[:space:]]+@#\1:***@#g'       -e 's#^([[:space:]]*(user|username|pass|password|token|secret|apiKey|api_key)[[:space:]]*:[[:space:]]*).*$#\1***#Ig'       "$f"
    echo
  done
} > "$OUT/mediamtx-redacted.txt" 2>&1

DB_LIST="$OUT/databases.txt"
: > "$DB_LIST"
for root in "${REPO:-/nonexistent}" /var/lib /opt; do
  [ -d "$root" ] || continue
  find "$root" -maxdepth 5 -type f \( -name "*.sqlite" -o -name "*.db" -o -name "*.sqlite3" \)     2>/dev/null | grep -Ei 'stream|media|ndm|auth|device|record' >> "$DB_LIST" || true
done
sort -u -o "$DB_LIST" "$DB_LIST"

mkdir -p "$OUT/sqlite"
while IFS= read -r db; do
  [ -f "$db" ] || continue
  name="$(printf '%s' "$db" | sed 's#/#_#g; s#^_##')"
  {
    echo "DB: $db"
    ls -lh "$db"
    if command -v sqlite3 >/dev/null 2>&1; then
      echo "=== INTEGRITY ==="
      sqlite3 "$db" 'PRAGMA integrity_check;' 2>&1 || true
      echo "=== TABLES ==="
      sqlite3 "$db" '.tables' 2>&1 || true
      echo "=== SCHEMA ==="
      sqlite3 "$db" '.schema' 2>&1 || true
      echo "=== COUNTS ==="
      for t in $(sqlite3 "$db" "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';" 2>/dev/null); do
        printf '%s: ' "$t"
        sqlite3 "$db" "SELECT COUNT(*) FROM \"$t\";" 2>/dev/null || true
      done
    fi
  } > "$OUT/sqlite/$name.txt" 2>&1
done < "$DB_LIST"

if [ -n "${REPO:-}" ] && [ -d "$REPO" ]; then
  grep -RniE     'CREATE TABLE|ALTER TABLE|users|persons|roles|groups|permissions|devices|device_groups|department|workplace|auth|sessions'     "$REPO" --include='*.py' --include='*.sql' --include='*.md' 2>/dev/null | head -4000 > "$OUT/domain-hints.txt" || true
fi

{
  [ -n "${REPO:-}" ] && ls -ld "$REPO" "$REPO"/data "$REPO"/config 2>/dev/null || true
  echo
  ss -lntup 2>/dev/null | grep -E ':(80|443|554|1935|8888|8889|8890|9997)\b' || true
} > "$OUT/runtime.txt"

tar -C "$OUT_BASE" -czf "$OUT_BASE/stream-manager-inventory-$TS.tar.gz" "$(basename "$OUT")"
printf 'Created: %s\n' "$OUT_BASE/stream-manager-inventory-$TS.tar.gz"
