#!/bin/sh
# OPTIONAL step of the read-only assessment, run by the CUSTOMER.
#
# The assessment reads your repository only. If you want it to also show
#   - which repository objects Flux actually applied (ownership), and
#   - which Flux Kustomizations are failing,
# run this script once per cluster and send us the files it writes.
# Skipping it is fine: the assessment works without it.
#
# What it does: ONE read-only call per cluster,
#   kubectl get kustomizations.kustomize.toolkit.fluxcd.io -A -o json
# It reads no Secret, no ConfigMap, no Pod, no log, and changes nothing.
# If jq is installed, the file keeps only the four fields we use
# (name, namespace, status.inventory, status.conditions). Without jq the
# file is the plain kubectl output; our census drops every other field
# before it reads anything. Look at the file before you send it.
#
# Usage: cluster-snapshot.sh <kube-context> [<kube-context> ...]
# Download: https://gitops.root.lease/assessment/cluster-snapshot.sh
# Output: flux-kustomizations-<context>.json in the current directory.
set -eu

[ "$#" -ge 1 ] || { echo "usage: $0 <kube-context> [<kube-context> ...]" >&2; exit 64; }
command -v kubectl >/dev/null 2>&1 || { echo "kubectl not found" >&2; exit 69; }

for context in "$@"; do
  safe=$(printf '%s' "$context" | tr -c 'A-Za-z0-9._-' '_')
  out="flux-kustomizations-$safe.json"
  if command -v jq >/dev/null 2>&1; then
    kubectl --context "$context" get kustomizations.kustomize.toolkit.fluxcd.io -A -o json \
      | jq '{apiVersion: "v1", kind: "List", items: [.items[] | {
              kind: "Kustomization",
              metadata: {name: .metadata.name, namespace: .metadata.namespace},
              status: {inventory: .status.inventory, conditions: .status.conditions}}]}' > "$out"
    mode="reduced with jq"
  else
    kubectl --context "$context" get kustomizations.kustomize.toolkit.fluxcd.io -A -o json > "$out"
    mode="plain kubectl output (jq not found)"
  fi
  echo "$out: $(grep -c '"Kustomization"' "$out" || true) Kustomization(s), $mode"
done
