#!/usr/bin/env bash
# scripts/juju-spaces-check.sh [MODEL]
#
# Read-only juju identity + per-model SPACE assertion. Spaces are per-model in Juju,
# so this runs AFTER 'juju add-model' and before 'juju deploy'. Default MODEL=openstack.
# Asserts the six D-052/D-053 spaces present and the five stale names absent.
#
# Pinned values come from scripts/lib-net.sh (single source of truth).
# Exit codes: 0 pass | 1 fatal (missing/stale spaces, or juju error) | 2 model not present yet

set -euo pipefail
shopt -s inherit_errexit 2>/dev/null || true
IFS=$'\n\t'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/lib-net.sh
. "$SCRIPT_DIR/lib-net.sh"

FATAL=0
fail() { echo "FAIL: $*" >&2; FATAL=$((FATAL+1)); }
pass() { echo "PASS: $*"; }
note() { echo "NOTE: $*"; }

MODEL="${1:-openstack}"
need_jq || exit 2

# whoami first, DIRECTLY (not in a command substitution) so an auth/macaroon
# password prompt can reach the terminal before any captured juju call.
echo "=== juju identity ==="
juju whoami || true
echo
echo "=== models ==="
juju models 2>&1 | sed 's/^/  /' || true
echo

# Is MODEL present? Strip any owner/ prefix; match the bare model name.
if ! juju models --format json 2>/dev/null | jq -r '.models[]?.name' 2>/dev/null | sed 's#.*/##' | grep -qx "$MODEL"; then
  note "model '$MODEL' not present yet -- run 'juju add-model $MODEL' first (spaces are per-model)"
  echo
  echo "Summary: model-absent (run add-model, then re-run this check)"
  exit 2
fi
pass "model '$MODEL' present"

echo
echo "=== spaces in model '$MODEL' (want six; none of the five stale) ==="
SPJSON="$(juju spaces -m "$MODEL" --format json)" || { fail "juju spaces failed (auth/macaroon? re-login or append </dev/tty)"; echo; echo "Summary: 1 fatal"; exit 1; }
echo "$SPJSON" | jq -r '.spaces[].name' | sort | sed 's/^/    /'

mapfile -t HAVE < <(echo "$SPJSON" | jq -r '.spaces[].name')
have_has() { local x; for x in "${HAVE[@]}"; do [ "$x" = "$1" ] && return 0; done; return 1; }

for s in "${SPACES6[@]}"; do
  if have_has "$s"; then pass "present: $s"; else fail "MISSING: $s (deploy fails 'space not found')"; fi
done
for s in "${STALE_SPACES[@]}"; do
  if have_has "$s"; then fail "STALE STILL PRESENT: $s (run 'juju reload-spaces -m $MODEL')"; fi
done

echo
echo "Summary: ${FATAL} fatal"
if [ "$FATAL" -gt 0 ]; then exit 1; fi
exit 0
