name: Build and Push Container

on:
  workflow_call:
    inputs:
      registry:
        required: true
        type: string
      registry_username:
        required: true
        type: string
      registry_password:
        required: true
        type: string
      titles:
        required: true
        type: string

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DOCKER_ORG: teacup
      DOCKER_LATEST: nightly
      RUNNER_TOOL_CACHE: /toolcache
    strategy:
      matrix:
        os: [3.20.0, 3.21.0, 3.22.0]
    steps:
      - name: "Build: checkout"
        uses: actions/checkout@v4

      - name: "Build: set up Docker buildx"
        uses: docker/setup-buildx-action@v3
        with:
          buildkitd-flags: --debug

      - name: "Build: login to registry"
        uses: docker/login-action@v3
        with:
          registry: ${{ inputs.registry }}
          username: ${{ inputs.registry_username }}
          password: ${{ inputs.registry_password }}

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ inputs.registry }}/${{ github.repository }}

      - name: Set Image Name
        env:
          myTITLE: ${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.title'] }}
        id: split
        run: echo "myTITLE=${myTITLE##*d_}" | tee -a "$GITHUB_ENV"

      # Build and push Docker images
      - name: "Build and push Docker image for each version"
        uses: docker/build-push-action@v5
        with:
          build-args: |
            VERSION=${{ matrix.os }}
            NAS_USER=dnke
          context: .
          push: true
          tags: |
            ${{ inputs.registry }}/${{ inputs.registry_username }}/${{ env.myTITLE }}:${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
            ${{ inputs.registry }}/${{ inputs.registry_username }}/${{ env.myTITLE }}:${{ matrix.os }}
            ${{ inputs.registry }}/${{ inputs.registry_username }}/${{ env.myTITLE }}:latest
          labels: ${{ steps.meta.outputs.labels }}
