#!/usr/bin/env bash

. $(dirname $0)/util
set -eu -o pipefail

: ${BUILDX_NOCACHE=}
: ${TEST_COVERAGE=}

importCacheFlags=""
if [ -n "$cacheRefFrom" ]; then
  if [ "$cacheType" = "local" ]; then
    for ref in $cacheRefFrom; do
      importCacheFlags="$importCacheFlags--cache-from=type=local,src=$ref "
    done
  fi
fi

iid="buildx-tests"
iidfile=$(mktemp -t docker-iidfile.XXXXXXXXXX)

coverageVol=""
coverageFlags=""
if [ "$TEST_COVERAGE" = "1" ]; then
  covdir="$(pwd)/coverage"
  mkdir -p "$covdir"
  coverageVol="-v $covdir:/coverage"
  coverageFlags="-coverprofile=/coverage/coverage.txt -covermode=atomic"
fi

buildxCmd build $importCacheFlags \
  --target "integration-tests" \
  --output "type=docker,name=$iid" \
  $currentcontext

cacheVolume="buildx-cache"
if ! docker inspect "$cacheVolume" > /dev/null 2>&1; then
  cacheVolume=$(docker create --name=buildx-cache -v /root/.cache -v /go/pkg/mod alpine)
fi

docker run --rm -v /tmp $coverageVol --volumes-from=$cacheVolume --privileged $iid go test $coverageFlags ${TESTFLAGS:--v} ${TESTPKGS:-./...}

if [ -n "$BUILDX_NOCACHE" ]; then
  docker rm -v $cacheVolume
fi

rm "$iidfile"
docker rmi $iid
