#!/usr/bin/env bash
# Deploys one image digest, but only when its signature and its SBOM attestation verify against
# cosign.pub. In a cluster an admission controller (Kyverno, Sigstore policy-controller) does this.
#   deploy.sh REGISTRY/orders@sha256:...
source "$(dirname "$0")/../lib.sh"
work devsecops
REF="$1"; PORT="${PORT:-18085}"
case "$REF" in *@sha256:*) ;; *) echo "refused: deploy a digest, not a tag ($REF)"; exit 1;; esac
cosign() { docker run --rm --network host -u 0 -v "$WORK:/w" -w /w gcr.io/projectsigstore/cosign:v2.4.1 "$@"; }

if ! cosign verify --key cosign.pub --insecure-ignore-tlog=true --allow-http-registry "$REF" > "$WORK/verify.json" 2> "$WORK/verify.err"; then
  echo "refused: no valid signature for $REF"; grep -m1 -i error "$WORK/verify.err" || true; exit 1
fi
if ! cosign verify-attestation --key cosign.pub --type cyclonedx --insecure-ignore-tlog=true \
     --allow-http-registry "$REF" > /dev/null 2>&1; then
  echo "refused: no valid SBOM attestation for $REF"; exit 1
fi
echo "signature and SBOM attestation verified for $REF"

docker rm -f cap-sec-orders > /dev/null 2>&1 || true
docker run -d --name cap-sec-orders -p "127.0.0.1:$PORT:8080" --read-only --cap-drop ALL \
  --security-opt no-new-privileges --memory 128m --cpus 0.5 --pids-limit 64 "$REF" > /dev/null
wait_for "http://127.0.0.1:$PORT/readyz" 30
echo "deployed: cap-sec-orders on http://127.0.0.1:$PORT"
