name: Build & Push DEV to DockerHub

on:
  pull_request:
    branches: [ dev ]
  push:
    branches: [ dev ]

permissions:
  contents: read

jobs:
  docker:
    runs-on: ubuntu-latest

    env:
      # PRs: single-arch build (faster). Push to dev: multi-arch.
      PLATFORMS: ${{ github.event_name == 'pull_request' && 'linux/amd64' || 'linux/amd64,linux/arm64' }}

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

      - name: Read VERSION and compute DEV tags
        run: |
          if [[ ! -f VERSION ]]; then echo "VERSION file missing"; exit 1; fi
          RAW=$(tr -d ' \n' < VERSION)
          if [[ -z "$RAW" ]]; then echo "VERSION empty"; exit 1; fi
          # Remove 'v' prefix if present for version number
          if [[ "$RAW" =~ ^v ]]; then NUM="${RAW#v}"; else NUM="$RAW"; fi
          
          # Get repository name (assumes format: owner/repo)
          REPO_NAME=$(echo "${GITHUB_REPOSITORY}" | cut -d'/' -f2)
          
          echo "VERSION_NUM=$NUM" >> $GITHUB_ENV
          echo "DEV_VERSION=${NUM}-dev" >> $GITHUB_ENV
          echo "DOCKER_REPO=${{ secrets.DOCKER_HUB_USERNAME }}/${REPO_NAME}" >> $GITHUB_ENV
          echo "DEV_TAGS=${{ secrets.DOCKER_HUB_USERNAME }}/${REPO_NAME}:${NUM}-dev,${{ secrets.DOCKER_HUB_USERNAME }}/${REPO_NAME}:dev" >> $GITHUB_ENV
          echo "Computed DEV_VERSION=${NUM}-dev"

      - name: Set up QEMU
        if: ${{ env.PLATFORMS == 'linux/amd64,linux/arm64' }}
        uses: docker/setup-qemu-action@v3

      - name: Set up Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to DockerHub
        if: ${{ github.event_name != 'pull_request' }}
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_TOKEN }}

      - name: Build & (maybe) push
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          platforms: ${{ env.PLATFORMS }}
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ env.DEV_TAGS }}
          build-args: |
            APP_VERSION=${{ env.DEV_VERSION }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: false
