name: Build and Push mc-webui image

on:
  push:
    branches: [main, dev]
  workflow_dispatch: # Manual trigger

env:
  IMAGE_NAME: mc-webui

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Freeze App Version
        run: python3 -m app.version freeze

      - name: Extract version tag
        id: get_tag
        run: |
          TAG_VALUE=$(grep "DOCKER_TAG =" app/version_frozen.py | cut -d'"' -f2)
          echo "Extracted Tag: $TAG_VALUE"
          echo "tag=$TAG_VALUE" >> $GITHUB_OUTPUT

      - name: Determine image tags
        id: tags
        run: |
          BRANCH="${GITHUB_REF##*/}"
          DH_IMAGE="${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}"
          OWNER_LC=$(echo "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')
          GH_IMAGE="ghcr.io/${OWNER_LC}/${{ env.IMAGE_NAME }}"
          TAG="${{ steps.get_tag.outputs.tag }}"

          if [ "$BRANCH" = "main" ]; then
            TAGS="${DH_IMAGE}:latest,${DH_IMAGE}:${TAG}"
            TAGS="${TAGS},${GH_IMAGE}:latest,${GH_IMAGE}:${TAG}"
          else
            TAGS="${DH_IMAGE}:${BRANCH},${DH_IMAGE}:${BRANCH}-${TAG}"
            TAGS="${TAGS},${GH_IMAGE}:${BRANCH},${GH_IMAGE}:${BRANCH}-${TAG}"
          fi

          echo "Generated tags: $TAGS"
          echo "tags=$TAGS" >> $GITHUB_OUTPUT

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile
          push: true
          platforms: linux/amd64,linux/arm64,linux/arm/v7
          tags: ${{ steps.tags.outputs.tags }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
