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

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
ENV_FILE="$ROOT/.env.load"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing $ENV_FILE; no observability project was selected." >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
. "$ENV_FILE"
set +a

: "${LOAD_PROJECT:?LOAD_PROJECT is missing from .env.load}"

if [[ "$LOAD_PROJECT" == "who_need_help" ]]; then
  echo "Refusing to stop services in the staging Compose project." >&2
  exit 1
fi

runtime_dir="$ROOT/tmp/observability/$LOAD_PROJECT"
export OBSERVABILITY_RUNTIME_DIR="$runtime_dir"

compose=(
  docker compose
  --env-file "$ENV_FILE"
  -p "$LOAD_PROJECT"
  -f compose.yaml
  -f compose.load.yaml
  -f compose.observability.yaml
  --profile observability
)

for service in alert-receiver alertmanager prometheus grafana; do
  while IFS= read -r container_id; do
    [[ -z "$container_id" ]] && continue
    observed_project=$(
      docker inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' \
        "$container_id"
    )
    observed_service=$(
      docker inspect --format '{{index .Config.Labels "com.docker.compose.service"}}' \
        "$container_id"
    )

    if [[ "$observed_project" != "$LOAD_PROJECT" ||
      "$observed_service" != "$service" ]]; then
      echo "Container scope mismatch for $container_id." >&2
      exit 1
    fi
  done < <("${compose[@]}" ps --all -q "$service")
done

"${compose[@]}" stop grafana prometheus alertmanager alert-receiver

echo "Stopped only the isolated observability services; app and metric volumes remain."
