#!/usr/bin/env bash

set -eu -o pipefail

: ${BUILDX_CMD=docker buildx}
: ${RELEASE_OUT=./release-out}
: ${CACHE_FROM=}
: ${CACHE_TO=}

if [ -n "$CACHE_FROM" ]; then
  for cfrom in $CACHE_FROM; do
    cacheFlags+=(--set "*.cache-from=$cfrom")
  done
fi
if [ -n "$CACHE_TO" ]; then
  for cto in $CACHE_TO; do
    cacheFlags+=(--set "*.cache-to=$cto")
  done
fi

# release
(set -x ; ${BUILDX_CMD} bake "${cacheFlags[@]}" --set "*.output=$RELEASE_OUT" release)

# wrap binaries
mv -f ./${RELEASE_OUT}/**/* ./${RELEASE_OUT}/
find ./${RELEASE_OUT} -type d -empty -delete

# checksums
if ! type shasum > /dev/null 2>&1; then
  echo >&2 "ERROR: shasum is required"
  exit 1
fi
find ./${RELEASE_OUT}/ -type f \( -iname "buildx-*" ! -iname "*darwin*" \) -print0 | sort -z | xargs -r0 shasum -a 256 -b | sed 's# .*/#  #' > ./${RELEASE_OUT}/checksums.txt

# verify
(
  cd ./${RELEASE_OUT}
  shasum -a 256 -U -c checksums.txt
)
