# source  latest
# dest    buildx-stable-1
# result  moby/buildkit:latest   > moby/buildkit:buildx-stable-1
#         moby/buildkit:rootless > moby/buildkit:buildx-stable-1-rootless
#
# source  v0.8.1
# dest    buildx-stable-1
# result  moby/buildkit:v0.8.1          > moby/buildkit:buildx-stable-1
#         moby/buildkit:v0.8.1-rootless > moby/buildkit:buildx-stable-1-rootless
name: buildx-image

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
  contents: read

on:
  workflow_dispatch:
    inputs:
      source-tag:
        description: 'BuildKit source Docker tag'
        required: true
        default: 'latest'
      dest-tag:
        description: 'Default BuildKit Docker tag for buildx'
        required: true
        default: 'buildx-stable-1'
      dry-run:
        description: 'Dry run'
        required: false
        default: 'true'

env:
  SETUP_BUILDX_VERSION: "edge"
  REPO_SLUG_TARGET: "moby/buildkit"

jobs:
  create:
    runs-on: ubuntu-24.04
    strategy:
      fail-fast: false
      matrix:
        flavor:
          - ''
          - 'rootless'
    steps:
      -
        name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
        with:
          version: ${{ env.SETUP_BUILDX_VERSION }}
          buildkitd-flags: --debug
      -
        name: Login to DockerHub
        if: github.event.inputs.dry-run != 'true'
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      -
        name: Create
        run: |
          DRYRUN_FLAG=""
          if [ "${{ github.event.inputs.dry-run }}" = "true" ]; then
            DRYRUN_FLAG="--dry-run"
          fi

          SOURCE_TAG="${{ github.event.inputs.source-tag }}"
          DEST_TAG="${{ github.event.inputs.dest-tag }}"
          if [ "${{ matrix.flavor }}" != "" ]; then
            if [ "$SOURCE_TAG" = "latest" ]; then
              SOURCE_TAG="${{ matrix.flavor }}"
            else
              SOURCE_TAG="${SOURCE_TAG}-${{ matrix.flavor }}"
            fi
            DEST_TAG="${DEST_TAG}-${{ matrix.flavor }}"
          fi

          set -x
          docker buildx imagetools create ${DRYRUN_FLAG} --tag \
            "${{ env.REPO_SLUG_TARGET }}:${DEST_TAG}" \
            "${{ env.REPO_SLUG_TARGET }}:${SOURCE_TAG}"
