#!/usr/bin/env bash
# ci-gate.sh <namespace>: kubeapt analyze as a CI gate that also fails when the
# run proved nothing. --pipeline alone only fails on Admitted probes, so a token
# that can't see anything (every probe Inconclusive) would pass.
# It also fails when a "Blocked" result has no admission enforcer behind it:
# KubeAPT 2.2.0 counts any 403/422 as a block, including quota, RBAC escalation
# prevention, and a namespace being deleted.
set -uo pipefail
kubeapt analyze -n "$1" -f json --output /tmp/analyze.json >/dev/null 2>&1
jq -e '.results.summary as $s
  | ($s.fail == 0) and ($s.byOutcome.Inconclusive // 0) == 0 and ($s.byOutcome.Error // 0) == 0
    and ($s.pass > 0)' /tmp/analyze.json >/dev/null
rc=$?
unattributed=$(jq '[.results.probes[] | select(.outcome == "Blocked")
  | select((.enforcedBy.type // "") | test("^(PodSecurity|ValidatingAdmissionPolicy|Webhook)$") | not)] | length' /tmp/analyze.json)
[ "$unattributed" -eq 0 ] || rc=1
jq -r --arg u "$unattributed" '.results.summary | "pass=\(.pass) fail=\(.fail) warn=\(.warn) inconclusive=\(.inconclusive) unattributed-blocks=\($u) \(.byOutcome|tojson)"' /tmp/analyze.json
exit $rc
