#!/usr/bin/env bash
# Read-only, metadata-only NGBVD production request monitor.
# Start it, then immediately refresh the /analysis page in the browser.
set -u
cd /var/www/html/ngbvd || exit 1
report="/tmp/ngbvd_analysis_live_$(date +%Y%m%d_%H%M%S).txt"
{
  echo "=== LIVE REPORT MONITOR ==="
  echo "Start: $(date -Is)"
  echo "Capture window: 90 seconds, every 10 seconds"
  for n in $(seq 1 9); do
    echo
    echo "=== SAMPLE $n of 9 | $(date -Is) ==="
    uptime
    free -m | head -n 3
    ps -eo comm,pid,%cpu,%mem,rss,etime --sort=-%cpu | grep -E '(^COMMAND|apache2|php-fpm|mysqld)' | head -n 18 || true
    # Use the existing authenticated Laravel DB connection to show metadata-only
    # active query timing. No raw SQL, user IDs, names, or case details emitted.
    php -r '
      require "vendor/autoload.php";
      $app=require "bootstrap/app.php";
      $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
      $db=Illuminate\Support\Facades\DB::connection();
      $db->disableQueryLog();
      try {
        foreach ($db->select("SELECT COMMAND AS cmd, TIME AS secs, STATE AS st FROM information_schema.PROCESSLIST WHERE DB=DATABASE() AND COMMAND <> ? ORDER BY TIME DESC LIMIT 8", ["Sleep"]) as $r) {
          echo "MYSQL seconds=".(int)($r->secs??0)." command=".($r->cmd??"")." state=".($r->st??"").PHP_EOL;
        }
      } catch (Throwable $e) { echo "MYSQL process metadata unavailable\n"; }
    ' 2>&1 | head -n 12
    if [ "$n" -lt 9 ]; then sleep 10; fi
  done
  echo "End: $(date -Is)"
} 2>&1 | tee "$report"
echo "Saved: $report"
echo "Share only after verifying that the file contains no sensitive information."
