name: Reusable build and test
on:
  workflow_call:
    inputs:
      pg_package:
        type: string
        required: true
      pg_version:
        type: string
        required: true
      os:
        type: string
        required: true
      compiler:
        type: string
        required: true
      build_type:
        type: string
        required: true

env:
  PG_PACKAGE: ${{ inputs.pg_package }}
  PG_VERSION: ${{ inputs.pg_version }}
  OS: ${{ inputs.os }}
  CC: ${{ inputs.compiler }}
  BUILD_TYPE: ${{ inputs.build_type }}
  PGPORT: 6432

jobs:
  build:
    name: Build
    runs-on: ${{ inputs.os }}
    timeout-minutes: 15
    steps:
      - name: Remove existing PostgreSQL
        if: startsWith(inputs.os, 'ubuntu-')
        run: sudo apt purge postgresql* libpq*

      - name: Clone repository
        uses: actions/checkout@v7
        with:
          path: src
          ref: ${{ github.ref }}

      - name: Install dependencies for Ubuntu
        if: startsWith(inputs.os, 'ubuntu-')
        run: src/.github/scripts/ubuntu-deps.sh

      - name: Install dev dependencies for Ubuntu
        if: startsWith(inputs.os, 'ubuntu-') && env.PG_PACKAGE == 'source'
        run: src/.github/scripts/ubuntu-deps.sh dev

      - name: Install dependencies for MacOS
        if: startsWith(inputs.os,  'macos-')
        run: src/.github/scripts/macos-deps.sh

      - name: Install PostgreSQL
        if: env.PG_PACKAGE != 'source'
        run: src/.github/scripts/install-postgresql.sh ${{ env.PG_PACKAGE }} ${{ env.PG_VERSION }}

      - name: Clone postgres repository
        if: env.PG_PACKAGE == 'source'
        uses: actions/checkout@v7
        with:
          path: postgres
          repository: postgres/postgres.git
          ref: REL_${{ env.PG_VERSION }}_STABLE

      - name: Build PostgreSQL
        if: env.PG_PACKAGE == 'source'
        run: src/.github/scripts/build-postgres.sh ${{ env.BUILD_TYPE }}

      - name: Build pg_stat_monitor
        run: src/.github/scripts/build.sh ${{ env.BUILD_TYPE }}

      - name: Run tests
        run: src/.github/scripts/test.sh ${{ env.BUILD_TYPE }}

      - name: Report on test fail
        uses: actions/upload-artifact@v4
        if: ${{ failure() }}
        with:
          name: log-test-${{ env.PG_PACKAGE }}-${{ env.PG_VERSION }}-${{ env.OS }}-${{ env.CC }}-${{ env.BUILD_TYPE }}
          path: |
            src/regression_install
            src/regression_install.log
            src/regression.diffs
            src/regression.out
            src/results
            src/t/results
            src/tmp_check
          retention-days: 3
