#!/bin/sh
# mcp-policy-bundle: build a signed OPA bundle from the policy logic
# shipped with mcp-gateway and the administrator's role data, for
# mcp-opa.service in signed bundle mode (docs/architecture.md, section
# 5.5). The bundle replaces the output file atomically; unless -n is
# given, mcp-opa.service is then restarted, which verifies the signature.
# With -G it creates a signing key pair on this host instead.
set -eu

usage() {
	cat <<USAGE
Usage: mcp-policy-bundle [-k SIGNING_KEY] [-o OUTPUT] [-r REVISION] [-n]
                         [-V VENDOR_POLICY_DIR] [-L LOCAL_POLICY_DIR]
       mcp-policy-bundle -G [-k SIGNING_KEY] [-o OUTPUT]

  -k  private key (PEM, RSA) to sign the bundle with
      (default: /etc/mcp-gateway/bundle/signing.pem); keeping it off the
      gateway host is safer, keeping it here allows signing from Cockpit
  -G  create a signing key pair: the private key at the -k path (mode
      0600) and the verification key as verify.pem next to OUTPUT
  -a  signing algorithm (default: RS256)
  -o  bundle file (default: /etc/mcp-gateway/bundle/policy.tar.gz)
  -r  revision recorded in the bundle (default: UTC timestamp)
  -n  do not restart mcp-opa.service
  -V  policy logic (default: /usr/share/mcp-gateway/policy)
  -L  the administrator's policy and role data (default:
      /etc/mcp-gateway/policy; in rbac/, data.yaml; no file in JSON, no
      longer read since 1.7)
  -D  the default role data, in force while LOCAL_POLICY_DIR/rbac has
      none (default: /usr/share/mcp-gateway/rbac/data.yaml; "": none)

Environment: OPA (default: opa from PATH), MCP_GATEWAY (default:
mcp-gateway from PATH; checks the role data before building, if found),
MCP_POLICY_RENDER (default: /usr/libexec/mcp-gateway/mcp-policy-render;
renders the role data as mcp-opa.service has it, if found).
-G needs openssl.
USAGE
	exit 2
}

key=/etc/mcp-gateway/bundle/signing.pem alg=RS256
out=/etc/mcp-gateway/bundle/policy.tar.gz
revision=$(date -u +%Y%m%dT%H%M%SZ) restart=yes genkey=no
vendor=/usr/share/mcp-gateway/policy local=/etc/mcp-gateway/policy
default=/usr/share/mcp-gateway/rbac/data.yaml
while getopts k:a:o:r:nGV:L:D:h opt; do
	case $opt in
	k) key=$OPTARG ;;
	G) genkey=yes ;;
	a) alg=$OPTARG ;;
	o) out=$OPTARG ;;
	r) revision=$OPTARG ;;
	n) restart=no ;;
	V) vendor=$OPTARG ;;
	L) local=$OPTARG ;;
	D) default=$OPTARG ;;
	*) usage ;;
	esac
done
opa=${OPA:-opa}
render=${MCP_POLICY_RENDER:-/usr/libexec/mcp-gateway/mcp-policy-render}

# relabel gives new files their SELinux label (e.g. mcpgw_signing_key_t).
relabel() {
	if command -v restorecon >/dev/null 2>&1; then
		restorecon -F "$@" 2>/dev/null || true
	fi
}

if [ "$genkey" = yes ]; then
	pub="$(dirname "$out")/verify.pem"
	if [ -e "$key" ]; then
		echo "mcp-policy-bundle: $key exists; not replacing it" >&2
		exit 1
	fi
	mkdir -p "$(dirname "$key")" "$(dirname "$pub")"
	(umask 077 && openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$key" 2>/dev/null)
	openssl pkey -in "$key" -pubout -out "$pub.new"
	chmod 0644 "$pub.new"
	mv -f "$pub.new" "$pub"
	relabel "$key" "$pub"
	echo "created signing key $key and verification key $pub"
	exit 0
fi

if [ ! -r "$key" ]; then
	echo "mcp-policy-bundle: cannot read signing key $key (create one with -G, or pass -k)" >&2
	exit 1
fi

# The role data must match its schema; mcp-gateway checks it where it is
# installed (a bundle built elsewhere, e.g. in CI, may lack it). It checks
# the file in force, data.yaml (a data.json alone is no longer read).
gateway=${MCP_GATEWAY:-mcp-gateway}
if [ -f "$local/rbac/data.yaml" ] && command -v "$gateway" >/dev/null 2>&1; then
	if ! "$gateway" --check-policy-data --policy-data "$local/rbac/data.json"; then
		echo "mcp-policy-bundle: the role data in $local/rbac has problems (above); no bundle built" >&2
		exit 1
	fi
fi

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
mkdir "$tmp/src"
cp -R "$vendor/." "$tmp/src/"
# The role data comes from the administrator's directory only.
rm -rf "$tmp/src/mcp/rbac"
# The administrator's files: Rego files at their relative path, so a file
# at a shipped path replaces the shipped one; data files below data.mcp,
# as mcp-opa.service loads them ("mcp:/etc/mcp-gateway/policy"). Below
# rbac/, as mcp-opa.service has it (mcp-policy-render): in each directory
# data.yaml only, as data.mcp.rbac; nothing else. With mcp-policy-render,
# the bundle carries what it renders, as OPA loads it in directory mode
# (YAML read as the gateway reads it, not by OPA's YAML parser); without
# it (a bundle built elsewhere), data.yaml as it is.
userender=no
command -v "$render" >/dev/null 2>&1 && userender=yes
(cd "$local" && find . -type f ! -name '.manifest') | while IFS= read -r f; do
	case $f in
	./rbac/*) [ "$userender" = no ] || continue ;;
	esac
	case $f in
	./rbac/*/data.json | ./rbac/data.json)
		y=${f%.json}.yaml
		if [ -f "$local/$y" ]; then
			echo "mcp-policy-bundle: $local/${f#./} is ignored: $local/${y#./} is in force" >&2
		else
			echo "$local/${f#./}" >>"$tmp/json"
		fi
		continue ;;
	./rbac/*/data.yaml | ./rbac/data.yaml) dest="$tmp/src/mcp/$f" ;;
	./rbac/*)
		echo "mcp-policy-bundle: $local/${f#./} is not role data (data.yaml); not in the bundle" >&2
		continue ;;
	*.json)
		echo "$local/${f#./}" >>"$tmp/json"
		continue ;;
	*/data.yaml | */data.yml) dest="$tmp/src/mcp/$f" ;;
	*) dest="$tmp/src/$f" ;;
	esac
	mkdir -p "$(dirname "$dest")"
	cp "$local/$f" "$dest"
done
# Configuration in JSON is no longer read (since 1.7): none goes into a
# bundle, and none is left out without saying so.
if [ -s "$tmp/json" ]; then
	while IFS= read -r f; do
		echo "mcp-policy-bundle: $f: configuration in JSON is no longer read since 1.7: convert it to YAML with mcp-gateway-admin policy convert $f" >&2
	done <"$tmp/json"
	echo "mcp-policy-bundle: no bundle built" >&2
	exit 1
fi
if [ "$userender" = yes ]; then
	rc=0
	"$render" -source "$local/rbac" -out "$tmp/src/mcp/rbac" -shipped "$vendor" -default "$default" || rc=$?
	case $rc in
	0) ;;
	3)
		echo "mcp-policy-bundle: role data in JSON in $local/rbac (above); no bundle built" >&2
		exit 1 ;;
	*)
		echo "mcp-policy-bundle: the role data in $local/rbac does not parse (above); no bundle built" >&2
		exit 1 ;;
	esac
# No role data of the administrator's: the shipped default, taken whole.
elif [ ! -f "$tmp/src/mcp/rbac/data.yaml" ] &&
	[ -n "$default" ] && [ -f "$default" ]; then
	mkdir -p "$tmp/src/mcp/rbac"
	cp "$default" "$tmp/src/mcp/rbac/data.yaml"
	echo "mcp-policy-bundle: no role data in $local/rbac: the shipped default $default is in force" >&2
fi
find "$tmp/src" -name '*_test.rego' -exec rm -f {} +
# The bundle claims only data.mcp, so it can share an OPA with other
# bundles; opa build rejects Rego packages and data outside it.
rm -f "$tmp/src/.manifest"
printf '{"roots": ["mcp"]}\n' >"$tmp/src/.manifest"

# From inside the tree: opa build records each file under the path it
# was given, and the temporary directory's would end up in every module
# id, changing the gateway's policy fingerprint at each build.
case $key in /*) ;; *) key=$PWD/$key ;; esac
case $opa in */*) case $opa in /*) ;; *) opa=$PWD/$opa ;; esac ;; esac
(cd "$tmp/src" && "$opa" check --strict . &&
	"$opa" build --bundle . --signing-key "$key" --signing-alg "$alg" \
		--revision "$revision" --output "$tmp/bundle.tar.gz")

mkdir -p "$(dirname "$out")"
cp "$tmp/bundle.tar.gz" "$out.new"
chmod 0644 "$out.new"
mv -f "$out.new" "$out"
relabel "$out"
echo "wrote $out (revision $revision)"

if [ "$restart" = yes ] && command -v systemctl >/dev/null 2>&1; then
	systemctl try-restart mcp-opa.service
fi
