#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "$SCRIPT_DIR/common.sh"

BRIEF=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --brief)
      BRIEF=1
      shift
      ;;
    -h|--help)
      echo "Usage: ./scripts/status.sh [--brief]"
      exit 0
      ;;
    *)
      die "unknown option: $1"
      ;;
  esac
done

load_env
host_arch="$(detect_host_arch)"
mode="$(arch_mode)"
echo "installer_root=$INSTALLER_ROOT"
echo "manifest_file=$MANIFEST_FILE"
echo "package_name=${package_name:-}"
echo "source_commit=${source_commit:-${git_commit:-}}"
echo "source_commit_short=${source_commit_short:-}"
echo "source_dirty=${source_dirty:-}"
echo "build_timestamp_utc=${build_timestamp_utc:-${created_at_utc:-}}"
echo "host_data_dir=$HOST_DATA_DIR"
echo "host_arch=$host_arch"
echo "package_arch=$PACKAGE_ARCH"
echo "package_platform=$PACKAGE_PLATFORM"
echo "allow_cross_arch=$ALLOW_CROSS_ARCH"
echo "arch_mode=$mode"
echo "runtime_image=$RPKI_IMAGE"
echo "runtime_platform=$RPKI_PLATFORM"
echo "runtime_image_revision=${runtime_image_revision:-}"
echo "runtime_image_dirty=${runtime_image_dirty:-}"
echo "metrics_image=$METRICS_IMAGE"
echo "metrics_platform=$METRICS_PLATFORM"
echo "metrics_image_revision=${metrics_image_revision:-}"
echo "metrics_image_dirty=${metrics_image_dirty:-}"
echo "rtr_report_dir=$RTR_REPORT_DIR"
echo "rtr_report_container_dir=$RTR_REPORT_CONTAINER_DIR"
echo "monitor_platform=$MONITOR_PLATFORM"
echo "rirs=${RIRS:-}"
echo "max_runs=${MAX_RUNS:-}"
echo "interval_secs=${INTERVAL_SECS:-}"
echo "periodic_snapshot_reset=${PERIODIC_SNAPSHOT_RESET:-0}"
echo "periodic_snapshot_max_deltas=${PERIODIC_SNAPSHOT_MAX_DELTAS:-100}"
echo
if command -v docker >/dev/null 2>&1; then
  docker version --format 'docker={{.Server.Version}}' 2>/dev/null || echo "docker=unavailable"
  docker compose version 2>/dev/null || true
  compose_cmd --profile core --profile sidecar --profile monitor ps || true
else
  echo "docker=missing"
fi
echo
df -h "$HOST_DATA_DIR" 2>/dev/null || true
echo
latest="$(latest_run_dir || true)"
if [[ -n "$latest" ]]; then
  echo "latest_run=$latest"
  print_run_summary "$latest" || true
else
  echo "latest_run=none"
fi
if [[ "$BRIEF" == "0" ]]; then
  echo
  endpoint_ok "http://127.0.0.1:${METRICS_PORT:-9556}/metrics" && echo "metrics=ok" || echo "metrics=unavailable"
  endpoint_ok "http://127.0.0.1:${PROMETHEUS_PORT:-9090}/-/ready" && echo "prometheus=ok" || echo "prometheus=unavailable"
  endpoint_ok "http://127.0.0.1:${GRAFANA_PORT:-3000}/api/health" && echo "grafana=ok" || echo "grafana=unavailable"
  echo
  if [[ "$RTR_REPORT_DIR" == "$HOST_DATA_DIR/empty-rtr-report" ]]; then
    echo "rtr_registration=fallback-empty-directory"
  else
    echo "rtr_registration=registered"
  fi
  echo "rtr_report_files=$(rtr_report_file_count "$RTR_REPORT_DIR")"
  echo "rtr_latest_report=$(latest_rtr_report_file "$RTR_REPORT_DIR" || true)"
fi
