#!/usr/bin/env bash
# Read-only collection of whitelisted NGBVD production tuning/settings.
# Writes one private text report under /tmp. Does not modify any configuration.
set -u
umask 077
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REPORT="/tmp/ngbvd_stack_config_$(date +%Y%m%d_%H%M%S).txt"
section() { printf '\n====== %s ======\n' "$1"; }
{
  section 'AUDIT METADATA'
  date -Is
  printf 'Project folder: %s\n' "$ROOT"
  printf 'Diagnostic only, no configuration or schema changes\n'
  section 'SERVER / OS'
  uname -srmo
  (lsb_release -ds 2>/dev/null || true)
  uptime
  getconf _NPROCESSORS_ONLN 2>/dev/null || true
  free -h
  swapon --show --noheadings 2>/dev/null || true
  df -hT / "$ROOT" 2>/dev/null || true
  df -i / "$ROOT" 2>/dev/null || true
  findmnt -no SOURCE,FSTYPE,OPTIONS / 2>/dev/null || true
  lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT 2>/dev/null || true
  section 'SERVER LIMITS'
  printf 'open_files_current_shell='; (ulimit -n || true)
  for key in vm.swappiness vm.dirty_ratio vm.dirty_background_ratio vm.overcommit_memory fs.file-max net.core.somaxconn; do
    v="$(sysctl -n "$key" 2>/dev/null || true)"; [ -z "$v" ] || printf '%s=%s\n' "$key" "$v"
  done
  section 'RESOURCE SNAPSHOT'
  vmstat 1 3 2>/dev/null || true
  ps -eo comm,%cpu,%mem,rss,etime --sort=-%cpu | head -18 || true
  if command -v iostat >/dev/null 2>&1; then iostat -dx 1 2 2>/dev/null || true; else echo 'iostat unavailable'; fi

  section 'APACHE ACTIVE MODULES / VALIDITY'
  (apache2ctl -t 2>&1 || true) | head -6
  (apache2ctl -M 2>/dev/null || true) | grep -Ei 'mpm_|php|proxy|fcgi|http2|deflate|brotli|reqtimeout|status|rewrite' || true
  printf 'Note: active mod_php does not prove every vhost uses mod_php; inspect handler lines below.\n'
  section 'APACHE WHITELISTED CONFIG (NO VHOST NAMES OR PASSWORDS)'
  if [ -d /etc/apache2 ]; then
    grep -RinE '^[[:space:]]*(Timeout|ProxyTimeout|KeepAlive|KeepAliveTimeout|MaxRequestWorkers|ServerLimit|ThreadsPerChild|MaxConnectionsPerChild|StartServers|MinSpareServers|MaxSpareServers|SetHandler|ProxyPassMatch|FcgidIOTimeout|FcgidBusyTimeout|php_(admin_)?value[[:space:]]+(memory_limit|max_execution_time|post_max_size|upload_max_filesize))([[:space:]]|$)' \
      /etc/apache2/apache2.conf /etc/apache2/conf-enabled /etc/apache2/mods-enabled /etc/apache2/sites-enabled 2>/dev/null | head -150 || true
  fi
  section 'PHP VERSIONS AND ACTIVE CLI SETTINGS'
  (php -v 2>/dev/null || true) | head -2
  php -r '$keys=["memory_limit","max_execution_time","max_input_time","default_socket_timeout","max_input_vars","post_max_size","upload_max_filesize","output_buffering","zlib.output_compression","opcache.enable","opcache.enable_cli","opcache.memory_consumption","opcache.validate_timestamps","realpath_cache_size","realpath_cache_ttl"]; echo "cli_sapi=".PHP_SAPI.PHP_EOL; echo "cli_loaded_ini=".(php_ini_loaded_file()?:"none").PHP_EOL; foreach($keys as $k)echo "CLI.$k=".ini_get($k).PHP_EOL;' 2>&1 || true
  section 'PHP APACHE/FPM INI FILE SETTINGS (WHITELIST ONLY; MAY BE OVERRIDDEN PER DIRECTORY)'
  php <<'PHP'
<?php
$keys=['memory_limit','max_execution_time','max_input_time','default_socket_timeout','max_input_vars','post_max_size','upload_max_filesize','output_buffering','zlib.output_compression','opcache.enable','opcache.memory_consumption','opcache.max_accelerated_files','opcache.validate_timestamps','realpath_cache_size','realpath_cache_ttl'];
foreach (glob('/etc/php/*/{apache2,fpm,cli}/php.ini', GLOB_BRACE) ?: [] as $file) {
    echo "SOURCE $file\n";
    $config = @parse_ini_file($file, false, INI_SCANNER_RAW);
    if (!is_array($config)) { echo "  unreadable\n"; continue; }
    foreach ($keys as $key) if (array_key_exists($key, $config)) echo "  $key=".(is_scalar($config[$key]) ? $config[$key] : '[complex]')."\n";
}
PHP
  section 'PHP-FPM POOLS (ONLY PROCESS LIMITS, NO ENVIRONMENT OR CREDENTIALS)'
  grep -RinE '^[[:space:]]*(pm[[:space:]]*=|pm\.(max_children|max_requests|start_servers|min_spare_servers|max_spare_servers)[[:space:]]*=|request_terminate_timeout[[:space:]]*=|request_slowlog_timeout[[:space:]]*=|php_(admin_)?value\[(memory_limit|max_execution_time)\][[:space:]]*=)' /etc/php/*/fpm/pool.d/*.conf 2>/dev/null | head -100 || true
  section 'PHP HANDLER AND ERROR LOG SIZES'
  for p in /var/log/apache2/error.log /var/log/php8.2-fpm.log "$ROOT/storage/logs/laravel.log"; do
    [ ! -e "$p" ] || stat -c '%n bytes=%s' "$p" 2>/dev/null || true
  done
  section 'MYSQL WHITELISTED EFFECTIVE VARIABLES / COUNTERS / TABLE METADATA'
  (cd "$ROOT" && php scripts/config_audit_mysql.php) 2>&1 || true
  section 'MYSQL WHITELISTED CONFIG FILE DIRECTIVES'
  if [ -d /etc/mysql ]; then
    grep -RinE '^[[:space:]]*(innodb_buffer_pool_size|innodb_buffer_pool_instances|innodb_log_file_size|innodb_redo_log_capacity|innodb_flush_method|innodb_io_capacity|max_connections|max_allowed_packet|tmp_table_size|max_heap_table_size|table_open_cache|thread_cache_size|long_query_time|slow_query_log|join_buffer_size|sort_buffer_size|wait_timeout|net_read_timeout|net_write_timeout)[[:space:]]*=' /etc/mysql 2>/dev/null | head -100 || true
  fi
  section 'COMPLETED'
  printf 'Report generated successfully. Review for private paths or hostnames before sharing.\n'
} > "$REPORT" 2>&1
chmod 600 "$REPORT" 2>/dev/null || true
printf 'Created private report: %s\n' "$REPORT"
