#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
CLUSTER=who-need-help
MARKER="$ROOT/.tools/${CLUSTER}.owned"
CONTROL_PLANE="${CLUSTER}-control-plane"

if [ ! -f "$MARKER" ]; then
  echo "The project ownership marker is absent; refusing to stop a kind cluster." >&2
  exit 1
fi

if ! docker inspect "$CONTROL_PLANE" >/dev/null 2>&1; then
  echo "The project-owned kind control-plane container does not exist."
  exit 0
fi

scope=$(
  docker inspect "$CONTROL_PLANE" \
    --format '{{index .Config.Labels "io.x-k8s.kind.cluster"}}:{{index .Config.Labels "io.x-k8s.kind.role"}}'
)

if [ "$scope" != "$CLUSTER:control-plane" ]; then
  echo "The kind control-plane container is outside this project's scope." >&2
  exit 1
fi

if [ "$(docker inspect "$CONTROL_PLANE" --format '{{.State.Running}}')" != true ]; then
  echo "The project-owned kind cluster is already stopped."
  exit 0
fi

docker stop "$CONTROL_PLANE" >/dev/null
echo "Stopped the project-owned kind cluster; its container and Kubernetes data remain."
