#!/usr/bin/env bash
# verify-bundle.sh <dir-with-policies.yaml-and-bindings.yaml> <bundle-label>
#
# Compares what is INSTALLED in the cluster against a pinned, known-good copy of a
# bundle (extracted from an archive whose sha256 you checked out of band).
# Prints every policy/binding whose spec differs, is missing, or is extra, and
# exits non-zero if anything does.
set -euo pipefail
dir=$1; bundle=$2
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT

# Drop server-side defaults (matchPolicy: Equivalent, failurePolicy: Fail, scope: "*", empty
# selectors) so only meaningful differences remain.
norm='def clean: walk(if type=="object" then
        (del(.matchPolicy | select(. == "Equivalent")) | del(.failurePolicy | select(. == "Fail")) | del(.scope | select(. == "*"))
         | with_entries(select(.value != {} and .value != [] and .value != null)))
      else . end);
      [.items[] | {(.kind + "/" + .metadata.name): (.spec | clean)}] | add'

kubectl create --dry-run=client -o json -f "$dir/policies.yaml" -f "$dir/bindings.yaml" \
  | jq -s '{items: .}' | jq "$norm" > "$tmp/want.json"
# Bindings carry a bundle=<name> label; the policies themselves do not, so every
# installed policy is fetched and the ones outside the bundle are ignored below.
{ kubectl get validatingadmissionpolicies -o json; \
  kubectl get validatingadmissionpolicybindings -l "bundle=$bundle" -o json; } \
  | jq -s '{items: (map(.items) | add)}' | jq "$norm" > "$tmp/have.json"

jq -rn --slurpfile w "$tmp/want.json" --slurpfile h "$tmp/have.json" '
  ($w[0] // {}) as $W | ($h[0] // {}) as $H
  | (($W + $H) | keys[]) as $k
  | select($W[$k] != null or ($k | startswith("ValidatingAdmissionPolicyBinding/")))
  | if   $H[$k] == null then "MISSING  \($k)"
    elif $W[$k] == null then "EXTRA    \($k)"
    elif $W[$k] != $H[$k] then "CHANGED  \($k)"
    else empty end' > "$tmp/diff.txt"

cat "$tmp/diff.txt"
n=$(wc -l < "$tmp/diff.txt" | tr -d ' ')
echo "checked $(jq length "$tmp/want.json") objects, $n differ"
[ "$n" -eq 0 ]
