name: Build and Push Docker Image

on:
  push:
    tags:
      - "v*"

env:
  DOCKER_IMAGE: motphys/motrixlab
  DOCKERFILE_PATH: docker

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

    steps:
      - name: Free up disk space
        run: |
          echo "Removing hosted toolcache..."
          sudo rm -rf /opt/hostedtoolcache || true

          echo "Removing .NET..."
          sudo rm -rf /usr/share/dotnet || true

          echo "Removing Android SDK..."
          sudo rm -rf /usr/local/lib/android || true

          echo "Removing GHC / Haskell..."
          sudo rm -rf /opt/ghc || true
          sudo rm -rf /usr/local/.ghcup || true

          echo "Docker prune (just in case runner had leftovers)..."
          sudo docker container prune -f || true
          sudo docker image prune -af || true
          sudo docker volume prune -f || true

          echo "################################"
          echo "Disk usage AFTER cleanup:"
          echo "################################"
          df -h

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

      - name: Extract version from pyproject.toml
        id: version
        run: |
          VERSION=$(grep '^version' pyproject.toml | head -1 | sed 's/version = "\(.*\)"/\1/' | tr -d '" ')
          echo "version=${VERSION}" >> $GITHUB_OUTPUT
          echo "Extracted version: ${VERSION}"

      - 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.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Extract metadata for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.DOCKER_IMAGE }}
          tags: |
            type=semver,pattern={{version}},prefix=v
            type=semver,pattern={{major}}.{{minor}},prefix=v
            type=raw,value=${{ steps.version.outputs.version }}
            type=raw,value=latest

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ${{ env.DOCKERFILE_PATH }}/Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=min
          provenance: false
