#!/usr/bin/env bash
set -euo pipefail

root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
cd "$root"

go_ci=.github/workflows/go-ci.yml
dev_publisher=.github/workflows/publish-l0-engine-dev-release.yml
gate=.github/workflows/l0-release-ci.yml
publisher=.github/workflows/trusted-publish-l0-engine-release.yml
policy=release/l0-engine-image-signing-policy.json
public_key=release/runtime-api-image-signing-public-key.pem

for file in "$go_ci" "$dev_publisher" "$gate" "$publisher" "$policy" "$public_key"; do
  test -f "$file" || { echo "missing L0 Engine release owner: $file" >&2; exit 1; }
done

for stale in \
  .github/workflows/publish-runtime-api-image.yml \
  .github/workflows/publish-runtime-worker-image.yml \
  .github/workflows/publish-integration-service-image.yml \
  .github/workflows/trusted-publish-runtime-api-image.yml \
  .github/workflows/trusted-publish-runtime-worker-image.yml \
  .github/workflows/trusted-publish-integration-service-image.yml \
  release/runtime-api-image-signing-policy.json \
  release/runtime-worker-image-signing-policy.json \
  release/integration-service-image-signing-policy.json; do
  if [[ -e "$stale" ]]; then
    echo "split L0 publisher path returned: $stale" >&2
    exit 1
  fi
done

for required in \
  'push:' \
  'branches: [main]' \
  'group: go-ci-${{ github.sha }}' \
  'uses: ./.github/workflows/l0-release-ci.yml' \
  'needs: [resolve-exact-main]' \
  'uses: pingcap-inc/NexusCRM/.github/workflows/trusted-publish-l0-engine-release.yml@e266f1309cea5ad9f675a4890dd7199b8aa4f8c9' \
  'source_ref: refs/heads/main' \
  'source_sha: ${{ needs.resolve-exact-main.outputs.target_sha }}' \
  'release_version: ${{ needs.resolve-exact-main.outputs.release_version }}' \
  'catalog_reconcile_source_sha: ${{ needs.l0-release-gate.outputs.catalog_reconcile_source_sha }}' \
  'catalog_reconcile_image_digest: ${{ needs.l0-release-gate.outputs.catalog_reconcile_image_digest }}'; do
  grep -Fq -- "$required" "$go_ci" || { echo "go-ci lost one-release flow: $required" >&2; exit 1; }
done

for required in \
  'name: Build L0 Engine images' \
  'run-name: Build L0 images / commit:${{ inputs.source_commit }}' \
  'workflow_dispatch:' \
  'source_commit:' \
  'ref: ${{ inputs.source_commit }}' \
  'main is built automatically by go-ci' \
  'test "$GITHUB_REF" = refs/heads/main' \
  'uses: ./.github/workflows/l0-release-ci.yml' \
  'uses: pingcap-inc/NexusCRM/.github/workflows/trusted-publish-l0-engine-release.yml@e266f1309cea5ad9f675a4890dd7199b8aa4f8c9' \
  'source_ref: ${{ needs.resolve.outputs.source_ref }}' \
  'source_sha: ${{ needs.resolve.outputs.source_sha }}'; do
  grep -Fq -- "$required" "$dev_publisher" || { echo "dev publisher lost invariant: $required" >&2; exit 1; }
done

if sed -n '/^  l0-release-gate:/,/^  publish-l0-engine-release:/p' "$go_ci" | grep -Eq 'source-backed-runtime-gate|backend-docker-image-smoke|build-test-seal'; then
  echo "L0 Engine release regained an L1 or whole-repository gate" >&2
  exit 1
fi

for forbidden in 'repository_dispatch:' 'workflow_run:' 'runtime-publication-receipt' 'l0-release-publication-receipt' 'trusted-publish-runtime-' 'trusted-publish-integration-'; do
  if grep -Fq -- "$forbidden" "$go_ci" "$dev_publisher" "$gate" "$publisher"; then
    echo "L0 Engine release regained a cross-workflow handoff: $forbidden" >&2
    exit 1
  fi
done

if grep -Fq -- 'uses: ./.github/workflows/trusted-publish-l0-engine-release.yml' "$go_ci" "$dev_publisher"; then
  echo "caller may not execute a same-commit privileged publisher" >&2
  exit 1
fi

for required in \
  'workflow_call:' \
  'source_sha:' \
  'source_ref:' \
  'release_version:' \
  'catalog_reconcile_source_sha:' \
  'catalog_reconcile_image_digest:' \
  'workflow_dispatch)' \
  'pingcap-inc/NexusCRM/.github/workflows/publish-l0-engine-dev-release.yml' \
  'nexuscrm.l0-engine-image-signing-policy/v2' \
  '$source_ref == "refs/heads/main"' \
  'test "$GITHUB_SHA" = "$SOURCE_SHA"' \
  'workflow="$GITHUB_WORKFLOW_REF"' \
  'role: [runtime-api, runtime-worker, integration-service]' \
  'pending-$SOURCE_SHA-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT' \
  'scripts/ci/runtime-image-smoke.sh' \
  'scripts/ci/integration-image-smoke.sh' \
  '"$candidate" init-l0' \
  'cosign attest' \
  'cosign sign' \
  'cosign verify-attestation' \
  'Bind the trusted main controller to the immutable source' \
  'git merge-base --is-ancestor "$SOURCE_SHA" refs/remotes/nexuscrm/release-source' \
  'fetch --no-tags origin "+$SOURCE_REF:refs/remotes/nexuscrm/release-source"' \
  'http.https://github.com/.extraheader=AUTHORIZATION: basic $auth' \
  'Log in to GitHub Container Registry for descriptor signing' \
  '--target release-descriptor' \
  'release-buildkit-predicates' \
  'nexuscrm.l0-engine-release/v1'; do
  grep -Fq -- "$required" "$publisher" || { echo "single L0 publisher lost invariant: $required" >&2; exit 1; }
done

if grep -Eq '^[[:space:]]+git fetch --no-tags' "$publisher"; then
  echo "publisher regained an unauthenticated current-main fetch" >&2
  exit 1
fi

for forbidden in 'workflow_dispatch:' 'pull_request:' 'api.github.com' 'gh run download' 'github.event.workflow_run' '@310344ac18b54cd0b7543e9c7c5780cbe05b00cc'; do
  if grep -Fq -- "$forbidden" "$publisher"; then
    echo "single L0 publisher regained stale authority: $forbidden" >&2
    exit 1
  fi
done

for required in \
  'workflow_call:' \
  'runtime-release-gate:' \
  'Prove the app-blind L0 source graph' \
  'scripts/ci/check-workspace-module-graphs.sh' \
  'tools/boundarygate' \
  'scripts/ci/check-runtime-process-boundary.sh' \
  'catalog_reconcile_source_sha:' \
  'catalog_reconcile_image_digest:'; do
  grep -Fq -- "$required" "$gate" || { echo "L0 gate lost invariant: $required" >&2; exit 1; }
done
for forbidden in 'push:' 'workflow_run:' 'packages: write' 'id-token: write' 'nexuscrm-app-packs' 'sfcrm'; do
  if grep -Fq -- "$forbidden" "$gate"; then
    echo "L0 gate gained release authority or L1 knowledge: $forbidden" >&2
    exit 1
  fi
done

jq -e '
  .schema_version == "nexuscrm.l0-engine-image-signing-policy/v2" and
  .publisher_state == "active" and
  .owner_repository == "pingcap-inc/NexusCRM" and
  .repository_id == "1218978506" and
  .caller_workflow_paths == [
    "pingcap-inc/NexusCRM/.github/workflows/go-ci.yml",
    "pingcap-inc/NexusCRM/.github/workflows/publish-l0-engine-dev-release.yml"
  ] and
  (.source_ref? == null) and (.caller_workflow_ref? == null) and
  .trusted_workflow_ref == "pingcap-inc/NexusCRM/.github/workflows/trusted-publish-l0-engine-release.yml@e266f1309cea5ad9f675a4890dd7199b8aa4f8c9" and
  (.subjects | keys | sort) == ["engine-release", "integration-service", "runtime-api", "runtime-worker"] and
  .subjects["engine-release"].image_repository == "ghcr.io/pingcap-inc/nexuscrm-l0-engine-release" and
  .subjects["runtime-api"].image_repository == "ghcr.io/pingcap-inc/nexuscrm-runtime-api" and
  .subjects["runtime-worker"].image_repository == "ghcr.io/pingcap-inc/nexuscrm-runtime-worker" and
  .subjects["integration-service"].image_repository == "ghcr.io/pingcap-inc/nexuscrm-integration-service" and
  .key_spec == "ECC_NIST_P256" and
  .key_usage == "SIGN_VERIFY" and
  .signing_algorithm == "ECDSA_SHA_256"
' "$policy" >/dev/null

openssl pkey -pubin -in "$public_key" -noout >/dev/null
if command -v sha256sum >/dev/null 2>&1; then
  key_sha=$(sha256sum "$public_key" | awk '{print $1}')
else
  key_sha=$(shasum -a 256 "$public_key" | awk '{print $1}')
fi
test "sha256:$key_sha" = "$(jq -r .public_key_sha256 "$policy")" || {
  echo "L0 Engine signing key does not match its one policy" >&2
  exit 1
}

node --test scripts/ci/l0-engine-release-source.test.js

echo "L0 Engine release boundary passed"
