name: Build Docker Image

on:
  push:
    branches:
      - staging
    tags:
      - "v*"
  workflow_dispatch:

jobs:
  build-backend:
    runs-on: docker

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Login to Docker registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | \
            docker login git.koppkb.com \
              -u "${{ secrets.REGISTRY_USERNAME }}" \
              --password-stdin

      - name: Build & push backend image
        run: |
          set -e

          IMAGE="git.koppkb.com/KoPKB/api_arrahn"
          TAGS="-t ${IMAGE}:${{ gitea.sha }}"

          if [ "${{ gitea.ref_type }}" = "tag" ] && echo "${{ gitea.ref_name }}" | grep -q '^v'; then
            TAGS="${TAGS} -t ${IMAGE}:${{ gitea.ref_name }}"
          fi

          if [ "${{ gitea.ref_name }}" = "staging" ]; then
            TAGS="${TAGS} -t ${IMAGE}:staging"
          fi

          echo "Building and pushing backend: ${TAGS}"
          docker buildx build \
            --target staging \
            --platform linux/amd64 \
            --cache-from type=registry,ref=${IMAGE}:buildcache,ignore-error=true \
            --cache-to type=registry,ref=${IMAGE}:buildcache,mode=max \
            -f docker/php/Dockerfile \
            ${TAGS} \
            --push .
