name: Build & Publish AMD Strix Halo Toolboxes

on:
  workflow_dispatch:
    inputs:
      backends:
        description: >
          Comma-separated backends to build (e.g. "rocm-7beta,rocm-7rc").
          Use "all" to build everything.
        required: false
        default: all

env:
  DOCKERHUB_REPO: docker.io/kyuz0/amd-strix-halo-toolboxes
  LOCAL_PREFIX: llama

jobs:
  # 1) Prepare a clean JSON array for the matrix
  prepare:
    runs-on: ubuntu-latest
    outputs:
      matrix_json: ${{ steps.mk.outputs.matrix_json }}
    steps:
      - id: mk
        shell: bash
        run: |
          # Input from the Run workflow form
          IN='${{ inputs.backends }}'

          if [[ "$IN" == "all" || -z "$IN" ]]; then
            JSON='["rocm-6.4.4","rocm-7.2.1","rocm7-nightlies","vulkan-amdvlk","vulkan-radv"]'
          else
            # Remove spaces and build JSON array from comma list
            IN_CLEAN=$(echo "$IN" | tr -d '[:space:]')
            JSON='["'${IN_CLEAN//,/\",\"}'"]'
          fi

          echo "matrix_json=${JSON}" >> "$GITHUB_OUTPUT"
          echo "Using matrix: ${JSON}"

  # 2) Build each backend in parallel using the prepared matrix
  build-and-push:
    needs: prepare
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        backend: ${{ fromJson(needs.prepare.outputs.matrix_json) }}

    steps:
      - name: Free up runner disk space
        run: |
          echo "Before cleanup:" && df -h /
          sudo rm -rf \
            /usr/share/dotnet \
            /usr/local/lib/android \
            /opt/ghc \
            /opt/hostedtoolcache/CodeQL
          docker system prune --all --force
          docker builder prune --all --force
          echo "After cleanup:" && df -h /

      - name: Check out repository
        uses: actions/checkout@v3

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

      - name: Set build timestamp
        run: echo "BUILD_TS=$(date +%Y%m%dT%H%M%S)" >> $GITHUB_ENV

      - name: Build & push ${{ matrix.backend }}
        working-directory: toolboxes
        shell: bash
        run: |
          set -euo pipefail
          B="${{ matrix.backend }}"
          DF="Dockerfile.$B"
          NAME="${B}"
          LI="${LOCAL_PREFIX}-${NAME}"
          TAG="${NAME}_${BUILD_TS}"
          IMM="${DOCKERHUB_REPO}:${TAG}"
          CHN="${DOCKERHUB_REPO}:${NAME}"

          echo "→ Building ${DF}"
          docker build --no-cache -t "${LI}" -f "${DF}" .

          echo "→ Tag & push immutable → ${IMM}"
          docker tag "${LI}" "${IMM}"
          docker push "${IMM}"

          echo "→ Tag & push channel → ${CHN}"
          docker tag "${IMM}" "${CHN}"
          docker push "${CHN}"
