#!/usr/bin/env bash
# Read-only diagnostics: how KORZILLA.Admin is run on the prod server.
# Changes nothing. Prints only variable NAMES from .env files, never values.
# Usage on the server (as root or via sudo):  bash whereis-prod.sh 2>&1 | tee whereis-prod.txt

section() { printf '\n========== %s ==========\n' "$1"; }
have() { command -v "$1" >/dev/null 2>&1; }

section "host"
hostname; uptime

section "who listens on 80/443/3000/4000/5432"
ss -ltnp 2>/dev/null | grep -E ':(80|443|3000|4000|5432)\b' || netstat -ltnp 2>/dev/null | grep -E ':(80|443|3000|4000|5432) '

section "docker containers"
if have docker; then
  docker ps -a --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
  for c in $(docker ps -aq); do
    docker inspect "$c" --format '{{.Name}}  cmd={{json .Config.Cmd}}  compose_dir={{index .Config.Labels "com.docker.compose.project.working_dir"}}  created={{.Created}}'
  done
else
  echo "docker not installed"
fi

section "systemd services"
systemctl list-units --type=service --all --no-pager 2>/dev/null | grep -iE 'korzilla|admin|next|nest|node|pm2|gitlab' || echo "no matching units"
for u in $(systemctl list-unit-files --no-pager 2>/dev/null | grep -iE 'korzilla|admin' | awk '{print $1}'); do
  echo "--- $u"; systemctl cat "$u" 2>/dev/null | grep -vE '^\s*Environment=.*(PASS|SECRET|TOKEN|KEY)'
done

section "pm2"
if have pm2; then pm2 ls; else echo "pm2 not installed"; fi

section "node processes (with working dir)"
for pid in $(pgrep -f 'node|next|nest' 2>/dev/null); do
  printf '%s  cwd=%s  cmd=%s\n' "$pid" "$(readlink /proc/$pid/cwd 2>/dev/null)" "$(tr '\0' ' ' < /proc/$pid/cmdline 2>/dev/null | cut -c1-200)"
done

section "nginx: admin.korzilla.ru"
if have nginx; then
  nginx -T 2>/dev/null | awk '/server_name/ && /admin\.korzilla/ {p=1} p {print} /^}/ {p=0}' | grep -E 'server_name|listen|location|proxy_pass|root' | head -40
else
  echo "nginx not installed"
fi

section "gitlab-runner"
if have gitlab-runner; then
  systemctl is-active gitlab-runner 2>/dev/null
  grep -E '^\s*(name|url|executor|builds_dir)\s*=' /etc/gitlab-runner/config.toml 2>/dev/null
else
  echo "gitlab-runner not installed"
fi

section "project checkouts"
for d in $(find / -xdev -maxdepth 5 -type f -name package.json \
             \( -path '*admin*' -o -path '*korzilla*' -o -path '*k-admin*' \) \
             -not -path '*/node_modules/*' 2>/dev/null | xargs -r -n1 dirname | sort -u); do
  echo "--- $d"
  grep -m1 '"name"' "$d/package.json"
  if [ -d "$d/.git" ]; then
    git -C "$d" remote -v 2>/dev/null | head -1
    git -C "$d" log -1 --format='HEAD: %h %ad %s' --date=iso 2>/dev/null
    echo "uncommitted changes:"; git -C "$d" status --short 2>/dev/null | head -30
  fi
  [ -f "$d/.env" ] && { echo ".env keys:"; grep -oE '^[A-Z_]+=' "$d/.env" | tr '\n' ' '; echo; }
  [ -f "$d/.env" ] && grep -E '^DATABASE_URL=' "$d/.env" | sed -E 's#(://[^:]+):[^@]*@#\1:***@#'
done
