name: Publish
on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+'
  workflow_dispatch:
    inputs:
      git_tag:
        required: true
        type: string
env:
  GIT_TAG: ${{ github.event.inputs.git_tag || github.ref_name }}
jobs:
  pgxn-test:
    strategy:
      matrix:
        pg: [19, 18, 17, 16, 15, 14, 13]
    runs-on: ubuntu-latest
    container: pgxn/pgxn-tools
    steps:
      - name: Initialize each Postgres version
        run: pg-start ${{ matrix.pg }}
      - name: Checkout specified tag
        uses: actions/checkout@v7
        with:
          ref: ${{ env.GIT_TAG }}
      - name: Test and build extension for Postgres
        run: pg-build-test
  pgxn-publish:
    needs: pgxn-test
    runs-on: ubuntu-latest
    container:
      image: pgxn/pgxn-tools
      env:
        PGXN_USERNAME: ${{ secrets.PGXN_USERNAME }}
        PGXN_PASSWORD: ${{ secrets.PGXN_PASSWORD }}
    steps:
      - name: Checkout specified tag
        uses: actions/checkout@v7
        with:
          ref: ${{ env.GIT_TAG }}
      - name: Build the extension bundle
        run: pgxn-bundle
      - name: Publish the extension to PGXN
        run: pgxn-release
  docker-publish:
    needs: pgxn-test
    runs-on: ubuntu-latest
    steps:
      - name: Checkout specified tag
        uses: actions/checkout@v7
        with:
          ref: ${{ env.GIT_TAG }}
      - name: Create version tag for Docker image
        run: |
          echo "BUILD_VERSION=$(echo ${GIT_TAG} | sed 's/^v//')" >> $GITHUB_ENV
      - name: Login to Github Container Registry
        uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Build and push tagged Docker image
        uses: docker/build-push-action@v7
        with:
          context: .
          load: true
          push: true
          tags: |
            ghcr.io/${{ github.repository }}:latest
            ghcr.io/${{ github.repository }}:${{ env.BUILD_VERSION }}
      - name: Run Docker image
        run: docker run --name pg_uuidv7 ghcr.io/${{ github.repository }} /bin/sh
      - name: Copy Docker container artifacts
        run: docker cp pg_uuidv7:/srv/ ./
      - name: Upload the latest artifacts to releases
        uses: ncipollo/release-action@v1
        with:
          allowUpdates: true
          artifacts: "srv/*"
          makeLatest: true
          name: ${{ env.GIT_TAG }}
          tag: ${{ env.GIT_TAG }}
