#!/usr/bin/env bash

: "${BUILDX_CMD=docker buildx}"
: "${BUILDX_BUILDER=}"

: "${GITHUB_ACTIONS=}"
: "${GITHUB_REPOSITORY=}"
: "${GITHUB_RUN_ID=}"
: "${GITHUB_TOKEN=}"

: "${CONTEXT=}"
: "${CACHE_FROM=}"
: "${CACHE_TO=}"

dockerCmd() {
  (
    set -x
    docker "$@"
  )
}

buildxCmd() {
  (
    set -x
    BUILDX_NO_DEFAULT_LOAD=true BUILDX_BUILDER="${BUILDX_BUILDER}" ${BUILDX_CMD} "$@"
  )
}

buildAttestFlags() {
  if ${BUILDX_CMD} build --help 2>&1 | grep -- '--attest' >/dev/null; then
    prvattrs="mode=max"
    if [ "$GITHUB_ACTIONS" = "true" ]; then
      prvattrs="$prvattrs,builder-id=https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
    fi
    echo "--attest=type=sbom --attest=type=provenance,$prvattrs"
  fi
}

currentcontext="."
cacheFromFlags=""
cacheToFlags=""
if [ "$GITHUB_ACTIONS" = "true" ] && [ "$GITHUB_REPOSITORY" = "moby/buildkit" ]; then
  currentcontext="https://github.com/$GITHUB_REPOSITORY.git#$GITHUB_REF"
  if [ -n "$CACHE_FROM" ]; then
    for cfrom in $CACHE_FROM; do
      if [[ $cfrom == *"type=gha"* ]]; then
        if [[ -n "$GITHUB_REPOSITORY" ]] && [[ $cfrom != *"repository="* ]]; then
          cfrom="${cfrom},repository=${GITHUB_REPOSITORY}"
        fi
        if [[ -n "$GITHUB_TOKEN" ]] && [[ $cfrom != *"ghtoken="* ]]; then
          cfrom="${cfrom},ghtoken=${GITHUB_TOKEN}"
        fi
      fi
      cacheFromFlags="${cacheFromFlags}--cache-from=$cfrom "
    done
  fi
  if [ -n "$CACHE_TO" ]; then
    for cto in $CACHE_TO; do
      if [[ $cto == *"type=gha"* ]]; then
        if [[ -n "$GITHUB_REPOSITORY" ]] && [[ $cto != *"repository="* ]]; then
          cto="${cto},repository=${GITHUB_REPOSITORY}"
        fi
        if [[ -n "$GITHUB_TOKEN" ]] && [[ $cto != *"ghtoken="* ]]; then
          cto="${cto},ghtoken=${GITHUB_TOKEN}"
        fi
      fi
      cacheToFlags="${cacheToFlags}--cache-to=$cto "
    done
  fi
fi
if [ -n "$CONTEXT" ]; then
  currentcontext=$CONTEXT
fi
