#!/usr/bin/env bash
# make-cluster-guards.sh: generate Deny bindings for the bundle's cluster-scoped
# RBAC/webhook/APIService/PV policies WITHOUT the opt-in objectSelector, so a new
# object cannot skip the check by leaving a label off. Objects that already
# violate today (Kubernetes' own system roles, mostly) are excluded by exact name,
# never by label, because labels are chosen by whoever creates the object.
set -euo pipefail
bundle=cenroq-best-practices
res='rbac.authorization.k8s.io/v1/clusterroles,rbac.authorization.k8s.io/v1/clusterrolebindings,admissionregistration.k8s.io/v1/validatingwebhookconfigurations,admissionregistration.k8s.io/v1/mutatingwebhookconfigurations,apiregistration.k8s.io/v1/apiservices,/v1/persistentvolumes'
kubeapt validate --bundle $bundle --ignore-bindings --policy-resources "$res" \
  --report all -f json --output /tmp/existing.json >/dev/null 2>&1 || true
policies='clusterrole-admission-api-control clusterrole-aggregation clusterrole-cert-auth-review
clusterrole-infra-cluster-resources clusterrole-nodes-proxy-get clusterrole-nonresource-urls
clusterrole-pod-exec-create clusterrole-pvc-write clusterrole-rbac-impersonate clusterrole-rbac-write
clusterrole-secrets-access clusterrole-serviceaccount-tokens clusterrole-serviceaccounts-write
clusterrole-wildcard-rules clusterrole-workloads-write clusterrolebinding-anonymous-subjects
clusterrolebinding-default-serviceaccount clusterrolebinding-powerful-roles clusterrolebinding-system-groups
mutatingwebhookconfiguration-hardening validatingwebhookconfiguration-hardening apiservice-tls
persistentvolume-hostpath'
for p in $policies; do
  # Resource rules the policy itself matches; reused for the name-based exclusions.
  rules=$(kubectl get validatingadmissionpolicy "$p" -o json | jq -c '.spec.matchConstraints.resourceRules')
  names=$(jq -c --arg p "$p" '[.results.namespaces[].violations[]? | select(.policy==$p)
          | .resource | split("/")[-1]] | unique' /tmp/existing.json)
  jq -n --arg p "$p" --argjson rules "$rules" --argjson names "$names" '{
    apiVersion: "admissionregistration.k8s.io/v1", kind: "ValidatingAdmissionPolicyBinding",
    metadata: {name: ("cluster-guard--" + $p), labels: {"guard": "cluster-scoped"}},
    spec: {policyName: $p, validationActions: ["Deny"],
      matchResources: (if ($names|length) == 0 then {} else
        {excludeResourceRules: [$rules[] | . + {resourceNames: $names}]} end)}}'
done | jq -s '{apiVersion: "v1", kind: "List", items: .}'
