# Publishes a release tag everywhere, in order: crates.io (rebac-schema, then rebacd); npm and the ghcr.io image; the
# GitHub Release's assets; PGXN; then it runs the served quickstart and deploys pgrebac.com from the tag. Every step
# skips what is already published, so a failed run is fixed by running it again. release-please.yml starts it when a
# release pull request is merged; by hand:
#
#   gh workflow run publish.yml --ref v0.3.0 -f tag=v0.3.0                  # dry run: builds and checks, publishes nothing
#   gh workflow run publish.yml --ref v0.3.0 -f tag=v0.3.0 -f dry-run=false
name: publish

on:
  workflow_dispatch:
    inputs:
      tag:
        description: Release tag, e.g. v0.3.0
        required: true
      dry-run:
        description: Build and check everything, publish nothing
        type: boolean
        default: true

concurrency:
  group: publish-${{ inputs.tag }}

permissions: {}

env:
  TAG: ${{ inputs.tag }}
  DRY_RUN: ${{ inputs.dry-run }}
  IMAGE: ghcr.io/${{ github.repository_owner }}/rebacd

jobs:
  # Checks the tag before anything is published (the release commit itself ran no CI), and works out what is missing.
  plan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    services:
      postgres:
        image: pgvector/pgvector:pg17
        env:
          POSTGRES_PASSWORD: rebac
        ports: ["55433:5432"]
        options: >-
          --health-cmd "pg_isready -U postgres" --health-interval 1s --health-timeout 5s --health-retries 30
    outputs:
      version: ${{ steps.version.outputs.version }}
      latest: ${{ steps.version.outputs.latest }}
      crates: ${{ steps.missing.outputs.crates }}
      npm: ${{ steps.missing.outputs.npm }}
      image: ${{ steps.missing.outputs.image }}
      pgxn: ${{ steps.missing.outputs.pgxn }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          fetch-depth: 0
          persist-credentials: false
      - id: version
        name: The tag names the version every manifest carries
        run: |
          version="${TAG#v}"
          git rev-parse -q --verify "refs/tags/$TAG" >/dev/null || { echo "$TAG is not a tag" >&2; exit 1; }
          [ "$DRY_RUN" = true ] || [ "$GITHUB_REF" = "refs/tags/$TAG" ] ||
            { echo "publish $TAG from its own tag: gh workflow run publish.yml --ref $TAG" >&2; exit 1; }
          cargo metadata --locked --no-deps --format-version 1 >/dev/null
          for v in "$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[].version' | sort -u)" \
                   "$(jq -r .version META.json)" "$(jq -r .provides.pg_rebac.version META.json)" \
                   "$(jq -r .version packages/npm/package.json)"; do
            [ "$v" = "$version" ] || { echo "$TAG, but a manifest says $v" >&2; exit 1; }
          done
          highest="$(git tag -l 'v*' --sort=-v:refname | head -1)"
          echo "version=$version" >> "$GITHUB_OUTPUT"
          echo "latest=$([ "$highest" = "$TAG" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
      - name: SQL suite
        env:
          REBAC_TEST_URL: postgres://postgres:rebac@127.0.0.1:55433
        run: tests/sql/run.sh
      - name: The release SQL installs on an empty database, and the quickstart names its SHA-256
        env:
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          sql="$(scripts/release-sql.sh "$VERSION")"
          psql postgres://postgres:rebac@127.0.0.1:55433/postgres -qc "create database artefact"
          psql -v ON_ERROR_STOP=1 -q postgres://postgres:rebac@127.0.0.1:55433/artefact -f "$sql" >/dev/null
          examples/quickstart/bundle.sh --check
          if [ "$(sed -n 's/^# pg_rebac version: //p' site/public/quickstart.yml)" = "$VERSION" ]; then
            grep -qx "# SQL SHA-256: $(sha256sum "$sql" | cut -d' ' -f1)" site/public/quickstart.yml ||
              { echo "site/public/quickstart.yml names another SHA-256 for $VERSION" >&2; exit 1; }
          fi
      - id: missing
        name: What is not yet published
        env:
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          missing() { "$@" >/dev/null 2>&1 && echo false || echo true; }
          {
            printf crates=
            for c in rebac-schema rebacd; do
              curl -fsS "https://index.crates.io/re/ba/$c" | jq -e --arg v "$VERSION" 'select(.vers == $v)' >/dev/null ||
                printf '%s ' "$c"
            done
            echo
            echo "npm=$(missing npm view "pg-rebac@$VERSION" version)"
            echo "image=$(missing docker buildx imagetools inspect "$IMAGE:$VERSION")"
            echo "pgxn=$(missing curl -fsS "https://api.pgxn.org/dist/pg_rebac/$VERSION/META.json")"
          } | tee -a "$GITHUB_OUTPUT"

  # Trusted publishing: crates.io exchanges this job's OIDC token for a token that lives as long as the job.
  # cargo publishes rebac-schema first and waits for the index before rebacd, which depends on it.
  crates:
    needs: plan
    if: needs.plan.outputs.crates
    runs-on: ubuntu-latest
    environment: release
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          persist-credentials: false
      - id: auth
        if: env.DRY_RUN == 'false'
        uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6
      - env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
          CRATES: ${{ needs.plan.outputs.crates }}
        run: |
          read -ra crates <<< "$CRATES"
          args=(--locked); for c in "${crates[@]}"; do args+=(-p "$c"); done
          [ "$DRY_RUN" = false ] || args+=(--dry-run)
          cargo publish "${args[@]}"

  # Trusted publishing with provenance: no token, no one-time password. Nothing waits on it, so a failure here (say,
  # the trusted publisher not yet set up) stops nothing else, and this job is re-run once npm is fixed.
  npm:
    needs: [plan, crates]
    if: ${{ !cancelled() && needs.plan.result == 'success' && needs.crates.result != 'failure' && needs.plan.outputs.npm == 'true' }}
    runs-on: ubuntu-latest
    environment: release
    permissions:
      contents: read
      id-token: write
    defaults:
      run:
        working-directory: packages/npm
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          persist-credentials: false
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with:
          node-version: 24
      - run: npm install --no-audit --no-fund --no-package-lock
      # A release from a maintenance branch must not move `latest`.
      - env:
          LATEST: ${{ needs.plan.outputs.latest }}
          VERSION: ${{ needs.plan.outputs.version }}
        run: |
          args=(--tag "$([ "$LATEST" = true ] && echo latest || echo "release-${VERSION%.*}")")
          [ "$DRY_RUN" = false ] || args+=(--dry-run)
          npm publish "${args[@]}"

  # Each architecture is built on its own runner and pushed by digest, with an SBOM and provenance attached.
  image-build:
    needs: [plan, crates]
    if: ${{ !cancelled() && needs.plan.result == 'success' && needs.crates.result != 'failure' && needs.plan.outputs.image == 'true' }}
    strategy:
      matrix:
        include:
          - { platform: linux/amd64, runner: ubuntu-24.04 }
          - { platform: linux/arm64, runner: ubuntu-24.04-arm }
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          persist-credentials: false
      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
      - if: env.DRY_RUN == 'false'
        uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ github.token }}
      - id: build
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: .
          platforms: ${{ matrix.platform }}
          outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=${{ env.DRY_RUN == 'false' }}
          sbom: true
          provenance: mode=max
          labels: |
            org.opencontainers.image.source=https://github.com/${{ github.repository }}
            org.opencontainers.image.licenses=Apache-2.0
            org.opencontainers.image.description=rebacd, the pg_rebac sync daemon: relays relationship writes to SpiceDB and keeps the projection in Postgres
            org.opencontainers.image.version=${{ needs.plan.outputs.version }}
            org.opencontainers.image.revision=${{ github.sha }}
          cache-from: type=gha,scope=${{ matrix.platform }}
          cache-to: type=gha,scope=${{ matrix.platform }},mode=max
      - run: mkdir -p /tmp/digests && touch "/tmp/digests/${DIGEST#sha256:}"
        env:
          DIGEST: ${{ steps.build.outputs.digest }}
      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: digest-${{ strategy.job-index }}
          path: /tmp/digests/*
          retention-days: 1

  # One multi-arch tag from the two digests, signed keyless with cosign (the signature names this workflow and tag).
  image:
    needs: [plan, image-build]
    if: ${{ !cancelled() && needs.image-build.result == 'success' && inputs.dry-run == false }}
    runs-on: ubuntu-latest
    permissions:
      packages: write
      id-token: write
    steps:
      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
        with:
          pattern: digest-*
          merge-multiple: true
          path: /tmp/digests
      - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ github.token }}
      - uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4
      - env:
          LATEST: ${{ needs.plan.outputs.latest }}
          VERSION: ${{ needs.plan.outputs.version }}
        working-directory: /tmp/digests
        run: |
          tags=(-t "$IMAGE:$VERSION"); [ "$LATEST" = false ] || tags+=(-t "$IMAGE:latest")
          sources=(); for d in *; do sources+=("$IMAGE@sha256:$d"); done
          docker buildx imagetools create "${tags[@]}" "${sources[@]}"
          digest="$(docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{json .Manifest}}' | jq -r .digest)"
          cosign sign --yes "$IMAGE@$digest"

  # The SQL, its checksums and the PGXN zip, attached to the Release that release-please created (or created here,
  # for a tag pushed by hand).
  github-release:
    needs: [plan, crates, image-build, image]
    if: ${{ !cancelled() && needs.plan.result == 'success' && !contains(needs.*.result, 'failure') }}
    runs-on: ubuntu-latest
    permissions:
      contents: write
    env:
      GH_TOKEN: ${{ github.token }}
      VERSION: ${{ needs.plan.outputs.version }}
      LATEST: ${{ needs.plan.outputs.latest }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          persist-credentials: false
      - run: make dist
      - run: cd dist && sha256sum "pg_rebac--$VERSION.sql" "pg_rebac-$VERSION.zip" | tee SHA256SUMS
      - if: env.DRY_RUN == 'false'
        run: |
          gh release view "$TAG" >/dev/null 2>&1 ||
            gh release create "$TAG" --verify-tag --title "pg_rebac $VERSION" --generate-notes
          gh release upload "$TAG" --clobber dist/"pg_rebac--$VERSION.sql" dist/"pg_rebac-$VERSION.zip" dist/SHA256SUMS
          gh release edit "$TAG" --latest="$LATEST"

  # PGXN Manager's upload form, with the account's credentials; the zip is the one attached to the Release. Without
  # credentials the job warns and leaves the upload to be done by hand.
  pgxn:
    needs: [plan, github-release]
    if: ${{ !cancelled() && needs.github-release.result == 'success' && needs.plan.outputs.pgxn == 'true' && inputs.dry-run == false }}
    runs-on: ubuntu-latest
    environment: release
    permissions:
      contents: read
    env:
      GH_TOKEN: ${{ github.token }}
      VERSION: ${{ needs.plan.outputs.version }}
    steps:
      - run: gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "pg_rebac-$VERSION.zip"
      - env:
          PGXN_USERNAME: ${{ secrets.PGXN_USERNAME }}
          PGXN_PASSWORD: ${{ secrets.PGXN_PASSWORD }}
        run: |
          [ -n "$PGXN_USERNAME" ] || { echo "::warning::No PGXN credentials: upload pg_rebac-$VERSION.zip from the Release at https://manager.pgxn.org/upload"; exit 0; }
          curl -fsS --user "$PGXN_USERNAME:$PGXN_PASSWORD" -H 'X-Requested-With: XMLHttpRequest' \
            --form-string 'submit=Release It!' -F "archive=@pg_rebac-$VERSION.zip" https://manager.pgxn.org/upload

  # What a reader runs: the one-file quickstart, against the image and SQL just published.
  quickstart:
    needs: [plan, github-release]
    if: ${{ !cancelled() && needs.github-release.result == 'success' && inputs.dry-run == false }}
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          persist-credentials: false
      - env:
          VERSION: ${{ needs.plan.outputs.version }}
        run: |
          [ "$(sed -n 's/^# pg_rebac version: //p' site/public/quickstart.yml)" = "$VERSION" ] ||
            { echo "::notice::site/public/quickstart.yml is not bundled for $VERSION; nothing to check"; exit 0; }
          docker compose -f site/public/quickstart.yml run --rm demo 2>&1 | tee out
          examples/quickstart/check-output.sh out

  # pgrebac.com is deployed from the latest release's tree, never from main, so the docs describe what is released.
  # A maintenance release that is not the latest leaves the site alone. Without a token the job warns and stops.
  site:
    needs: [plan, quickstart]
    if: ${{ !cancelled() && needs.quickstart.result == 'success' && needs.plan.outputs.latest == 'true' && inputs.dry-run == false }}
    runs-on: ubuntu-latest
    environment: release
    permissions:
      contents: read
    env:
      VERCEL_ORG_ID: team_xSm5id21v5bGUARdPAlzyCM4
      VERCEL_PROJECT_ID: prj_fFpLXPpsmjD6SWybv3znuHOCN2TY # pgrebac-site
      VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tag }}
          persist-credentials: false
      - run: |
          [ -n "$VERCEL_TOKEN" ] || { echo "::warning::No VERCEL_TOKEN: deploy pgrebac.com from $TAG by hand"; exit 0; }
          npx --yes vercel@66.6.0 deploy --prod --yes --token "$VERCEL_TOKEN"
