name: Build Docker Images

on:
  push:
    branches:
      - main
    tags:
      - "v*"

jobs:
  build:
    runs-on: ubuntu-latest-16c64g
    strategy:
      matrix:
        target: [webui, server]
        backend: [cuda, cpu]
    steps:
      - uses: actions/checkout@v4
      
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
      
      - name: Get Version
        run: |
          if [[ $GITHUB_REF == refs/tags/v* ]]; then
            version=$(basename ${GITHUB_REF})
          else
            version=nightly
          fi
          echo "version=${version}" >> $GITHUB_ENV
          echo "Current version: ${version}"

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USER }}
          password: ${{ secrets.DOCKER_PAT }}

      - name: Set platform for CPU builds
        id: platform
        run: |
          if [ "${{ matrix.backend }}" = "cpu" ]; then
            echo "platforms=linux/amd64,linux/arm64" >> $GITHUB_OUTPUT
          else
            echo "platforms=linux/amd64" >> $GITHUB_OUTPUT
          fi

      - name: Build and Push ${{ matrix.target }}-${{ matrix.backend }} Image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: docker/Dockerfile
          platforms: ${{ steps.platform.outputs.platforms }}
          push: true
          target: ${{ matrix.target }}
          build-args: |
            BACKEND=${{ matrix.backend }}
            UV_EXTRA=${{ matrix.backend == 'cuda' && 'cu126' || 'cpu' }}
          tags: |
            fishaudio/fish-speech:${{ matrix.target }}-${{ matrix.backend }}-${{ env.version }}
            fishaudio/fish-speech:${{ matrix.target }}-${{ matrix.backend }}
            ${{ (matrix.target == 'webui' && matrix.backend == 'cuda') && format('fishaudio/fish-speech:{0}', env.version) || '' }}
            ${{ (matrix.target == 'webui' && matrix.backend == 'cuda') && 'fishaudio/fish-speech:latest' || '' }}
          outputs: type=image,oci-mediatypes=true,compression=zstd,compression-level=3,force-compression=true
          cache-from: type=registry,ref=fishaudio/fish-speech:${{ matrix.target }}-${{ matrix.backend }}
          cache-to: type=inline

  update-readme:
    runs-on: ubuntu-latest
    needs: build
    if: github.ref == 'refs/heads/main'
    steps:
      - name: Push README to Dockerhub
        uses: peter-evans/dockerhub-description@v4
        with:
          username: ${{ secrets.DOCKER_USER }}
          password: ${{ secrets.DOCKER_PAT }}
          repository: fishaudio/fish-speech
