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: [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@v3
        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@v3
        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@v3
        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@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Build and push tagged Docker image
        uses: docker/build-push-action@v3
        with:
          context: .
          push: true
          tags: |
            ghcr.io/${{ github.repository }}:latest
            ghcr.io/${{ github.repository }}:${{ env.BUILD_VERSION }}
