#!/usr/bin/env bash
# scripts/checks/d011-01-charms.sh -- D-011 item 1: all charms active/idle.
# Focused check (NOT the cloud-assert behavioral sweep -- that is all-or-nothing and
# covers other D-011 items too; this asserts exactly "active/idle" per the D-011 wording).
# Toleration: carried gss units in workload 'unknown' are accepted (documented in
# cloud-assert A0; a known-benign carried state on this cloud).
# Exit (standard contract): 0 PASS | 1 FAIL (a unit not active/idle) | 2 HOLD (juju/jq
# unavailable or model unreachable -- cannot determine, not a charm failure).
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/lib-validate.sh
. "$HERE/../lib-validate.sh"
ID=d011-01-charms; vr_begin "$ID"
MODEL="${VR_MODEL:-openstack}"

vr_need juju jq || { emit "$ID" "$VR_HOLD" "missing tool (juju/jq)"; exit "$VR_HOLD"; }
if ! vr_json ST juju status -m "$MODEL" --format json; then
  vr_err_tail; emit "$ID" "$VR_HOLD" "model '$MODEL' unreachable (cannot determine)"; exit "$VR_HOLD"
fi
# validate JSON parses before trusting it
if ! jq -e . >/dev/null 2>&1 <<<"$ST"; then
  emit "$ID" "$VR_HOLD" "juju status did not return parseable JSON"; exit "$VR_HOLD"
fi

WALK="$(jq -r '
  .applications // {} | to_entries[] | .value.units // {} | to_entries[] |
    "\(.key) \(.value["workload-status"].current // "?") \(.value["juju-status"].current // "?")",
    (.value.subordinates // {} | to_entries[] | "\(.key) \(.value["workload-status"].current // "?") \(.value["juju-status"].current // "?")")
' <<<"$ST")"
[ -n "$WALK" ] || { emit "$ID" "$VR_HOLD" "no units found in model '$MODEL'"; exit "$VR_HOLD"; }

BAD=""
while read -r unit wl agent; do
  [ -n "$unit" ] || continue
  # documented toleration: carried gss unit in workload 'unknown'
  if [[ "$unit" == gss/* ]] && [ "$wl" = unknown ]; then
    echo "  tolerate: $unit workload=unknown (carried gss, documented)"; continue
  fi
  if [ "$wl" != active ] || [ "$agent" != idle ]; then
    echo "  NOT active/idle: $unit workload=$wl agent=$agent"
    BAD="$BAD $unit"
  fi
done <<<"$WALK"

N="$(grep -c . <<<"$WALK")"
if [ -n "$BAD" ]; then
  emit "$ID" "$VR_FAIL" "units not active/idle:$BAD"; exit "$VR_FAIL"
fi
emit "$ID" "$VR_PASS" "all $N units active/idle (gss-unknown tolerated)"; exit "$VR_PASS"
