# Release on a `v*` tag: check the tag against the Cargo version, generate the SQL artefact, run the SQL suite,
# attach the SQL to a GitHub Release, and push the rebacd image to ghcr.io (amd64 + arm64).
# crates.io, npm and PGXN are published by hand (docs: RELEASING in the release notes).
name: release
on:
  push:
    tags: ["v*"]
permissions:
  contents: read

jobs:
  sql:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    services:
      postgres:
        image: pgvector/pgvector:pg17
        env:
          POSTGRES_PASSWORD: rebac
        ports: ["55433:5432"]
        options: >-
          --health-cmd "pg_isready -U postgres" --health-interval 2s --health-retries 30
    steps:
      - uses: actions/checkout@v4
      - name: Tag matches the Cargo workspace version
        run: |
          version="$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name=="rebacd") | .version')"
          [ "v$version" = "$GITHUB_REF_NAME" ] || { echo "tag $GITHUB_REF_NAME != Cargo version v$version" >&2; exit 1; }
          echo "VERSION=$version" >> "$GITHUB_ENV"
      - name: Generate the SQL artefact
        run: scripts/release-sql.sh "$VERSION"
      - name: SQL tests
        env:
          REBAC_TEST_URL: postgres://postgres:rebac@127.0.0.1:55433
        run: tests/sql/run.sh
      - name: Install the artefact on an empty database
        run: |
          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 "dist/pg_rebac--$VERSION.sql" >/dev/null
      - name: Create the GitHub Release
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh release create "$GITHUB_REF_NAME" "dist/pg_rebac--$VERSION.sql" \
            --repo "$GITHUB_REPOSITORY" --title "pg_rebac $VERSION" --generate-notes --verify-tag
