name: Build and/or push api docker images (reusable workflow)

on:
  workflow_call:
    inputs:
      images:
        description: "The json array specifying image data (built with prepare-docker workflow)"
        required: true
        type: string
      version:
        description: "release version"
        required: true
        type: string
      publish:
        description: "Specifies whether to publish the images (defaults to false)"
        required: false
        type: boolean
        default: false
      artifact:
        description: "Upload docker artifact (defaults to false)"
        required: false
        type: boolean
        default: false

jobs:
  docker:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJSON(inputs.images) }}
    steps:
      - name: Checkout all repos with ref fallback
        uses: walt-id/waltid-identity/.github/actions/checkout-repos@29f904ce0de831e02fe64507ebe284b02e66b50e
        with:
          token: ${{ secrets.GH_ACCESS_TOKEN }}
      - name: Configure gradle
        uses: walt-id/waltid-identity/.github/actions/gradle-setup-action@a4a92e12ee9b7396ee9a22083ff21b3277c627d6
      - name: Patch *.gradle.kts for CI paths
        run: |
          sed -i '/allprojects {/,/}/{s/version = ".*"/version = "${{ inputs.version }}"/}' build.gradle.kts

      - name: Build Docker images (${{ matrix.image }})
        run: ./gradlew ${{ matrix.commandPath }}:publishImageToLocalRegistry
        env:
          MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }}
          MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
      - name: Publish Docker images (${{ matrix.image }})
        if: ${{ inputs.publish }}
        run: ./gradlew ${{ matrix.commandPath }}:publishImage
        env:
          DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
          DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
          MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }}
          MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}

      - name: Save Docker Image to ${{ matrix.image }}.tar.gz
        if: ${{ inputs.artifact }}
        run: docker save waltid/${{ matrix.image }}:${{ inputs.version }} | gzip > ${{ runner.temp }}/${{ matrix.image }}.tar.gz
        continue-on-error: false
      - name: Upload artifact
        if: ${{ inputs.artifact }}
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.image }}
          path: ${{ runner.temp }}/${{ matrix.image }}.tar.gz
          retention-days: 1
