name: Release

on:
  push:
    tags:
      - 'v*'
  # Manual (re)publish of an EXISTING tag. A tag-only trigger cannot be
  # retried after a workflow bug: `gh run rerun` re-executes the workflow
  # DEFINITION the tag was pushed under, so a fix on main never applies, and
  # re-tagging would rewrite published history. v0.1.3-alpha needed exactly
  # this after the pg_config bug below.
  workflow_dispatch:
    inputs:
      tag:
        description: 'Existing release tag to (re)build, e.g. v0.1.3-alpha'
        required: true
        type: string

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    name: Build Extension
    runs-on: ubuntu-latest
    strategy:
      matrix:
        # Every major pg_infer claims to support needs a binary here,
        # or the release page silently offers PG18 only.
        pg_version: [18, 19]
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ inputs.tag || github.ref }}

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Install system deps
        run: sudo apt-get update -qq && sudo apt-get install -y libopenblas-dev libreadline-dev zlib1g-dev pkg-config

      - name: Install cargo-pgrx
        run: cargo install cargo-pgrx --version 0.19.4 --locked

      - name: Initialize pgrx
        run: cargo pgrx init --pg${{ matrix.pg_version }} download

      - name: Build extension (release)
        run: |
          # NOT `which pg_config`: that finds the runner's preinstalled
          # PostgreSQL (16), and pgrx derives the feature name from the
          # pg_config it is given, so it then demands a `pg16` feature this
          # crate does not declare. Use the install pgrx just built.
          # Ask pgrx where its pg_config is, rather than globbing ~/.pgrx.
          # Globbing is wrong twice over: the directory is named for the
          # version pgrx installed (`18.7`, or `19rc2` while PG19's tarball
          # was a release candidate), and a build registered from OUTSIDE
          # pgrx -- `cargo pgrx init --pg19 /path/to/pg_config`, which is how
          # a GA PostgreSQL 19 gets tested -- creates NO directory there at
          # all. `info pg-config` answers correctly in both cases.
          PGC=$(cargo pgrx info pg-config pg${{ matrix.pg_version }})
          if [ -z "$PGC" ] || [ ! -x "$PGC" ]; then
            echo "::error::cargo pgrx has no usable pg_config for pg${{ matrix.pg_version }} (got '${PGC:-}')"
            exit 1
          fi
          echo "using $PGC ($("$PGC" --version))"
          cargo pgrx package --pg-config "$PGC"

      - name: Package artifact
        run: |
          TAG="${{ inputs.tag || github.ref_name }}"; VERSION="${TAG#v}"
          ARTIFACT="pg_infer-${VERSION}-pg${{ matrix.pg_version }}-x86_64-linux"
          mkdir -p "${ARTIFACT}"
          # `|| true` here used to swallow a wrong path and ship an EMPTY
          # tarball, which looks like a successful release. Fail instead.
          src="target/release/pg_infer-pg${{ matrix.pg_version }}"
          if [ ! -d "$src" ]; then
            echo "::error::$src does not exist; cargo pgrx package wrote somewhere else"
            ls -d target/release/pg_infer-* 2>/dev/null || true
            exit 1
          fi
          # `cargo pgrx package` mirrors the BUILDER's absolute prefix into
          # the staging dir, so a naive copy ships paths like
          # `home/runner/.pgrx/18.7/pgrx-install/lib/...` -- meaningless on
          # the user's machine and different again when PG19 is a build we
          # registered from elsewhere. Flatten to the layout a user can act
          # on, and tell them where it goes.
          so=$(find "$src" -name 'pg_infer.so' | head -1)
          sql=$(find "$src" -name 'pg_infer--*.sql' | head -1)
          ctl=$(find "$src" -name 'pg_infer.control' | head -1)
          for f in "$so" "$sql" "$ctl"; do
            if [ -z "$f" ]; then
              echo "::error::incomplete package in $src (need .so, install sql, and .control)"
              find "$src" -type f | head -20
              exit 1
            fi
          done
          mkdir -p "${ARTIFACT}/lib" "${ARTIFACT}/share/extension"
          cp "$so" "${ARTIFACT}/lib/"
          cp "$sql" "$ctl" "${ARTIFACT}/share/extension/"
          {
            printf '# pg_infer %s for PostgreSQL %s\n\n' \
              "${VERSION}" "${{ matrix.pg_version }}"
            printf 'Built against PostgreSQL %s on x86_64 Linux\n' \
              "${{ matrix.pg_version }}"
            printf '(ubuntu-latest). A pgrx extension is tied to the major it\n'
            printf 'was compiled for; do not use this with a different major.\n\n'
            printf 'This .so links libssl/libcrypto DYNAMICALLY (via\n'
            printf 'native-tls), so it needs an OpenSSL 3.x whose exported\n'
            printf 'symbols match the build distro. Debian and Ubuntu work.\n'
            printf 'Fedora does NOT: its OpenSSL omits some ciphers Ubuntu\n'
            printf 'exports, and loading fails with e.g. "undefined symbol:\n'
            printf 'EVP_sm4_cfb128". On such a distro, build from source:\n'
            printf '    cargo install cargo-pgrx --version 0.19.4 --locked\n'
            printf '    cargo pgrx install --release\n\n'
            printf '    sudo install -m 755 lib/pg_infer.so "$(pg_config --pkglibdir)/"\n'
            printf '    sudo install -m 644 share/extension/* "$(pg_config --sharedir)/extension/"\n\n'
            printf 'Then, in the database:\n\n'
            printf '    CREATE EXTENSION pg_infer;\n'
          } > "${ARTIFACT}/INSTALL.md"
          tar czf "${ARTIFACT}.tar.gz" "${ARTIFACT}"
          echo "packaged $(du -h "${ARTIFACT}.tar.gz" | cut -f1)"
          tar tzf "${ARTIFACT}.tar.gz"

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: pg_infer-pg${{ matrix.pg_version }}-x86_64-linux
          path: pg_infer-*.tar.gz

  release:
    name: Create GitHub Release
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          merge-multiple: true

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          # Without an explicit tag_name this attaches to github.ref, which on a
          # workflow_dispatch run is the BRANCH, not the release tag.
          tag_name: ${{ inputs.tag || github.ref_name }}
          generate_release_notes: true
          files: |
            *.tar.gz

  # Queue a postgresql.org news article for moderation (never auto-published;
  # see ci/announce.sh). Patch releases are skipped by the script unless their
  # changes carry a "### Security" section.
  announce:
    name: Announce to PostgreSQL news/announce
    needs: [release]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0   # announce.sh reads the commits since the previous tag
          ref: ${{ inputs.tag || github.ref }}
      - name: Announce to PostgreSQL news/announce
        env:
          PGORG_USER: ${{ secrets.PGORG_USER }}
          PGORG_PASSWORD: ${{ secrets.PGORG_PASSWORD }}
          PGORG_ORG_ID: ${{ secrets.PGORG_ORG_ID }}
          PGORG_EMAIL_ID: ${{ secrets.PGORG_EMAIL_ID }}
          PGORG_TAGS: ${{ secrets.PGORG_TAGS }}
        run: |
          if [ -z "$PGORG_USER" ] || [ -z "$PGORG_PASSWORD" ]; then
            echo "PGORG_USER/PGORG_PASSWORD secrets not set; skipping announcement."
            exit 0
          fi
          TAG="${{ inputs.tag || github.ref_name }}"; bash ci/announce.sh "${TAG#v}"
