name: Create and publish Docker images with specific build args

on:
  workflow_dispatch:
  push:
    branches:
      - main
      - dev
    tags:
      - v*

env:
  REGISTRY: ghcr.io

jobs:
  build-main-image:
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      packages: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: linux/amd64
            runner: ubuntu-latest
          - platform: linux/arm64
            runner: ubuntu-24.04-arm

    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Prepare
        run: |
          platform=${{ matrix.platform }}
          echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV

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

      - 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 the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (default latest tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}

      - name: Extract metadata for Docker cache
        id: cache-meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
          flavor: |
            prefix=cache-${{ matrix.platform }}-
            latest=false

      - name: Build Docker image (latest)
        uses: docker/build-push-action@v5
        id: build
        with:
          context: .
          push: true
          platforms: ${{ matrix.platform }}
          labels: ${{ steps.meta.outputs.labels }}
          outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
          cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
          cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
          sbom: true
          build-args: |
            BUILD_HASH=${{ github.sha }}

      - name: Export digest
        run: |
          mkdir -p /tmp/digests
          digest="${{ steps.build.outputs.digest }}"
          touch "/tmp/digests/${digest#sha256:}"

      - name: Upload digest
        uses: actions/upload-artifact@v4
        with:
          name: digests-main-${{ env.PLATFORM_PAIR }}
          path: /tmp/digests/*
          if-no-files-found: error
          retention-days: 1

  build-cuda-image:
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      packages: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: linux/amd64
            runner: ubuntu-latest
          - platform: linux/arm64
            runner: ubuntu-24.04-arm

    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Prepare
        run: |
          platform=${{ matrix.platform }}
          echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV

      - name: Delete huge unnecessary tools folder
        run: rm -rf /opt/hostedtoolcache

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

      - 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 the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (cuda tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-cuda,onlatest=true

      - name: Extract metadata for Docker cache
        id: cache-meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
          flavor: |
            prefix=cache-cuda-${{ matrix.platform }}-
            latest=false

      - name: Build Docker image (cuda)
        uses: docker/build-push-action@v5
        id: build
        with:
          context: .
          push: true
          platforms: ${{ matrix.platform }}
          labels: ${{ steps.meta.outputs.labels }}
          outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
          cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
          cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
          sbom: true
          build-args: |
            BUILD_HASH=${{ github.sha }}
            USE_CUDA=true

      - name: Export digest
        run: |
          mkdir -p /tmp/digests
          digest="${{ steps.build.outputs.digest }}"
          touch "/tmp/digests/${digest#sha256:}"

      - name: Upload digest
        uses: actions/upload-artifact@v4
        with:
          name: digests-cuda-${{ env.PLATFORM_PAIR }}
          path: /tmp/digests/*
          if-no-files-found: error
          retention-days: 1

  build-cuda126-image:
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      packages: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: linux/amd64
            runner: ubuntu-latest
          - platform: linux/arm64
            runner: ubuntu-24.04-arm

    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Prepare
        run: |
          platform=${{ matrix.platform }}
          echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV

      - name: Delete huge unnecessary tools folder
        run: rm -rf /opt/hostedtoolcache

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

      - 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 the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (cuda126 tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda126
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-cuda126,onlatest=true

      - name: Extract metadata for Docker cache
        id: cache-meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
          flavor: |
            prefix=cache-cuda126-${{ matrix.platform }}-
            latest=false

      - name: Build Docker image (cuda126)
        uses: docker/build-push-action@v5
        id: build
        with:
          context: .
          push: true
          platforms: ${{ matrix.platform }}
          labels: ${{ steps.meta.outputs.labels }}
          outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
          cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
          cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
          sbom: true
          build-args: |
            BUILD_HASH=${{ github.sha }}
            USE_CUDA=true
            USE_CUDA_VER=cu126

      - name: Export digest
        run: |
          mkdir -p /tmp/digests
          digest="${{ steps.build.outputs.digest }}"
          touch "/tmp/digests/${digest#sha256:}"

      - name: Upload digest
        uses: actions/upload-artifact@v4
        with:
          name: digests-cuda126-${{ env.PLATFORM_PAIR }}
          path: /tmp/digests/*
          if-no-files-found: error
          retention-days: 1

  build-ollama-image:
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      packages: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: linux/amd64
            runner: ubuntu-latest
          - platform: linux/arm64
            runner: ubuntu-24.04-arm

    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Prepare
        run: |
          platform=${{ matrix.platform }}
          echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV

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

      - 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 the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (ollama tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-ollama,onlatest=true

      - name: Extract metadata for Docker cache
        id: cache-meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
          flavor: |
            prefix=cache-ollama-${{ matrix.platform }}-
            latest=false

      - name: Build Docker image (ollama)
        uses: docker/build-push-action@v5
        id: build
        with:
          context: .
          push: true
          platforms: ${{ matrix.platform }}
          labels: ${{ steps.meta.outputs.labels }}
          outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
          cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
          cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
          sbom: true
          build-args: |
            BUILD_HASH=${{ github.sha }}
            USE_OLLAMA=true

      - name: Export digest
        run: |
          mkdir -p /tmp/digests
          digest="${{ steps.build.outputs.digest }}"
          touch "/tmp/digests/${digest#sha256:}"

      - name: Upload digest
        uses: actions/upload-artifact@v4
        with:
          name: digests-ollama-${{ env.PLATFORM_PAIR }}
          path: /tmp/digests/*
          if-no-files-found: error
          retention-days: 1

  build-slim-image:
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      packages: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: linux/amd64
            runner: ubuntu-latest
          - platform: linux/arm64
            runner: ubuntu-24.04-arm

    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Prepare
        run: |
          platform=${{ matrix.platform }}
          echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV

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

      - 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 the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (slim tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=slim
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-slim,onlatest=true

      - name: Extract metadata for Docker cache
        id: cache-meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
          flavor: |
            prefix=cache-slim-${{ matrix.platform }}-
            latest=false

      - name: Build Docker image (slim)
        uses: docker/build-push-action@v5
        id: build
        with:
          context: .
          push: true
          platforms: ${{ matrix.platform }}
          labels: ${{ steps.meta.outputs.labels }}
          outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
          cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
          cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
          sbom: true
          build-args: |
            BUILD_HASH=${{ github.sha }}
            USE_SLIM=true

      - name: Export digest
        run: |
          mkdir -p /tmp/digests
          digest="${{ steps.build.outputs.digest }}"
          touch "/tmp/digests/${digest#sha256:}"

      - name: Upload digest
        uses: actions/upload-artifact@v4
        with:
          name: digests-slim-${{ env.PLATFORM_PAIR }}
          path: /tmp/digests/*
          if-no-files-found: error
          retention-days: 1

  merge-main-images:
    runs-on: ubuntu-latest
    needs: [build-main-image]
    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Download digests
        uses: actions/download-artifact@v5
        with:
          pattern: digests-main-*
          path: /tmp/digests
          merge-multiple: true

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

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (default latest tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}

      - name: Create manifest list and push
        working-directory: /tmp/digests
        run: |
          docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
            $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)

      - name: Inspect image
        run: |
          docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}

  merge-cuda-images:
    runs-on: ubuntu-latest
    needs: [build-cuda-image]
    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Download digests
        uses: actions/download-artifact@v5
        with:
          pattern: digests-cuda-*
          path: /tmp/digests
          merge-multiple: true

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

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (default latest tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-cuda,onlatest=true

      - name: Create manifest list and push
        working-directory: /tmp/digests
        run: |
          docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
            $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)

      - name: Inspect image
        run: |
          docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}

  merge-cuda126-images:
    runs-on: ubuntu-latest
    needs: [build-cuda126-image]
    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Download digests
        uses: actions/download-artifact@v5
        with:
          pattern: digests-cuda126-*
          path: /tmp/digests
          merge-multiple: true

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

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (default latest tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda126
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-cuda126,onlatest=true

      - name: Create manifest list and push
        working-directory: /tmp/digests
        run: |
          docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
            $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)

      - name: Inspect image
        run: |
          docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}

  merge-ollama-images:
    runs-on: ubuntu-latest
    needs: [build-ollama-image]
    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Download digests
        uses: actions/download-artifact@v5
        with:
          pattern: digests-ollama-*
          path: /tmp/digests
          merge-multiple: true

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

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (default ollama tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-ollama,onlatest=true

      - name: Create manifest list and push
        working-directory: /tmp/digests
        run: |
          docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
            $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)

      - name: Inspect image
        run: |
          docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}

  merge-slim-images:
    runs-on: ubuntu-latest
    needs: [build-slim-image]
    steps:
      # GitHub Packages requires the entire repository name to be in lowercase
      # although the repository owner has a lowercase username, this prevents some people from running actions after forking
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

      - name: Download digests
        uses: actions/download-artifact@v5
        with:
          pattern: digests-slim-*
          path: /tmp/digests
          merge-multiple: true

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

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata for Docker images (default slim tag)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.FULL_IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=tag
            type=sha,prefix=git-
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=slim
          flavor: |
            latest=${{ github.ref == 'refs/heads/main' }}
            suffix=-slim,onlatest=true

      - name: Create manifest list and push
        working-directory: /tmp/digests
        run: |
          docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
            $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)

      - name: Inspect image
        run: |
          docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}

  # Copy images from GHCR to Docker Hub (best-effort, won't block GHCR)
  copy-to-dockerhub:
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')
    needs: [merge-main-images, merge-cuda-images, merge-cuda126-images, merge-ollama-images, merge-slim-images]
    continue-on-error: true
    strategy:
      fail-fast: false
      matrix:
        include:
          - variant: main
            suffix: ""
          - variant: cuda
            suffix: "-cuda"
          - variant: cuda126
            suffix: "-cuda126"
          - variant: ollama
            suffix: "-ollama"
          - variant: slim
            suffix: "-slim"
    steps:
      - name: Set repository and image name to lowercase
        run: |
          echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
          echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
        env:
          IMAGE_NAME: '${{ github.repository }}'

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

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Determine source and destination tags
        id: tags
        run: |
          DOCKERHUB_IMAGE="openwebui/open-webui"
          SUFFIX="${{ matrix.suffix }}"

          if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
            # For version tags: copy version tag and major.minor tag
            VERSION="${{ github.ref_name }}"
            VERSION="${VERSION#v}"
            MAJOR_MINOR="${VERSION%.*}"

            echo "tags<<EOF" >> $GITHUB_OUTPUT
            echo "${VERSION}${SUFFIX}" >> $GITHUB_OUTPUT
            echo "${MAJOR_MINOR}${SUFFIX}" >> $GITHUB_OUTPUT
            echo "EOF" >> $GITHUB_OUTPUT
          else
            # For main branch
            if [ -z "$SUFFIX" ]; then
              echo "tags=latest" >> $GITHUB_OUTPUT
            else
              # e.g. latest-cuda -> also tag as just "cuda"
              VARIANT_NAME="${SUFFIX#-}"
              echo "tags<<EOF" >> $GITHUB_OUTPUT
              echo "latest${SUFFIX}" >> $GITHUB_OUTPUT
              echo "${VARIANT_NAME}" >> $GITHUB_OUTPUT
              echo "EOF" >> $GITHUB_OUTPUT
            fi
          fi

          echo "dockerhub_image=${DOCKERHUB_IMAGE}" >> $GITHUB_OUTPUT

      - name: Copy images from GHCR to Docker Hub
        run: |
          DOCKERHUB_IMAGE="${{ steps.tags.outputs.dockerhub_image }}"
          SUFFIX="${{ matrix.suffix }}"

          # Determine the source tag on GHCR
          if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
            VERSION="${{ github.ref_name }}"
            VERSION="${VERSION#v}"
            SOURCE_TAG="${VERSION}${SUFFIX}"
          else
            if [ -z "$SUFFIX" ]; then
              SOURCE_TAG="latest"
            else
              SOURCE_TAG="latest${SUFFIX}"
            fi
          fi

          SOURCE="${{ env.FULL_IMAGE_NAME }}:${SOURCE_TAG}"

          echo "Copying from ${SOURCE} to Docker Hub..."

          # Copy each destination tag
          while IFS= read -r TAG; do
            [ -z "$TAG" ] && continue
            DEST="${DOCKERHUB_IMAGE}:${TAG}"
            echo "  -> ${DEST}"
            docker buildx imagetools create -t "${DEST}" "${SOURCE}"
          done <<< "${{ steps.tags.outputs.tags }}"
