name: Build Containers

on:
  # time has no specific meaning, trying to time it after
  # the llama.cpp daily packages are published
  # https://github.com/ggml-org/llama.cpp/blob/master/.github/workflows/docker.yml
  schedule:
    - cron: "37 5 * * *"

  # Allows manual triggering of the workflow
  workflow_dispatch:

  # Run on workflow file changes (without pushing)
  push:
    paths:
      - '.github/workflows/containers.yml'
      - 'docker/build-container.sh'
      - 'docker/*.Containerfile'

# grant permissions on GITHUB_TOKEN to publish packages
# ref: https://docs.github.com/en/packages/managing-github-packages-using-github-actions-workflows/publishing-and-installing-a-package-with-github-actions#publishing-a-package-using-an-action
permissions:
  contents: read
  packages: write
  id-token: write

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        platform: [intel, cuda, cuda13, vulkan, cpu, musa, rocm]
      fail-fast: false
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Free up disk space
        if: matrix.platform == 'rocm'
        run: |
          echo "Before cleanup:"
          df -h
          sudo rm -rf /usr/share/dotnet
          sudo rm -rf /usr/local/lib/android
          sudo rm -rf /opt/ghc
          sudo rm -rf /opt/hostedtoolcache/CodeQL
          sudo docker system prune -af
          echo "After cleanup:"
          df -h

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

      - name: Run build-container
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: ./docker/build-container.sh ${{ matrix.platform }} ${{ github.event_name != 'push' }}

  # note make sure mostlygeek/llama-swap has admin rights to the llama-swap package
  # see: https://github.com/actions/delete-package-versions/issues/74
  delete-untagged-containers:
    needs: build-and-push
    runs-on: ubuntu-latest
    steps:
      - uses: actions/delete-package-versions@v5
        with:
          package-name: 'llama-swap'
          package-type: 'container'
          delete-only-untagged-versions: 'true'
