#!/usr/bin/env bash
set -euo pipefail

PORT="${1:-8808}"

echo "== Local Webserver Reachability Diagnostics =="
echo "Date: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"

run_if() {
  local cmd="$1"
  shift
  if command -v "$cmd" >/dev/null 2>&1; then
    "$cmd" "$@"
  else
    echo "(missing command: $cmd)"
  fi
}

echo
echo "[1] Local process/service"
run_if systemctl --no-pager --full status local-webserver.service || true

echo
echo "[2] Local health check"
if command -v curl >/dev/null 2>&1; then
  ok=0
  for _ in 1 2 3 4 5; do
    if curl -sS -i "http://127.0.0.1:${PORT}/health"; then
      ok=1
      break
    fi
    sleep 1
  done
  if [[ "${ok}" -ne 1 ]]; then
    echo "Local health check failed after retries."
  fi
else
  echo "(missing command: curl)"
fi

echo
echo "[3] Listening sockets for port ${PORT}"
if command -v ss >/dev/null 2>&1; then
  ss -ltnp | awk 'NR==1 || /:'"${PORT}"'\\b/'
elif command -v netstat >/dev/null 2>&1; then
  netstat -ltnp 2>/dev/null | awk 'NR==1 || /:'"${PORT}"'\\b/'
else
  echo "(missing ss/netstat)"
fi

echo
echo "[4] Host IP addresses"
run_if hostname -I || true

echo
echo "[5] Docker published ports"
if command -v docker >/dev/null 2>&1; then
  docker ps --format 'table {{.Names}}\t{{.Ports}}'
else
  echo "(docker not installed)"
fi

echo
echo "[6] Firewall rules (ufw)"
if command -v ufw >/dev/null 2>&1; then
  ufw status || true
else
  echo "(ufw not installed)"
fi

echo
echo "Done. If [2] fails, app/service is not healthy locally."
echo "If [2] passes but remote fails, check [5] port publish, [6] firewall, and LAN routing/isolation."
