#!/bin/bash
set -e

IMAGE=jc21/gotools:latest

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$DIR/../.common.sh"

BUILD_DATE=$(date '+%Y-%m-%d %T %Z')
NOW=$(date --rfc-3339=s)
cd $DIR/../..

if [ "$BUILD_COMMIT" = "" ]; then
	BUILD_COMMIT=$(git log -n 1 --format=%h)
fi

if [ "$BUILD_VERSION" = "" ]; then
	BUILD_VERSION=$(cat .version)
fi

echo -e "${BLUE}❯ ${GREEN}test-backend: ${YELLOW}${1:-}${RESET}"
echo "  BUILD_COMMIT:  ${BUILD_COMMIT:-notset}"
echo "  BUILD_DATE:    $BUILD_DATE"
echo "  BUILD_VERSION: $BUILD_VERSION"
echo "  CGO_ENABLED:   ${CGO_ENABLED:-not set}"
echo "  GO111MODULE:   ${GO111MODULE:-}"
echo "  GOPRIVATE:     ${GOPRIVATE:-}"
echo "  GOPROXY:       ${GOPROXY:-}"
echo "  NOW:           $NOW"

if [ "${1:-}" = "--inside-docker" ]; then
	trap cleanup EXIT
	cleanup() {
		rm -f "/tmp/coverage.out"
		chown -R 1000:1000 "$DIR/../../test/results"
	}

	mkdir -p /workspace
	echo -e "${BLUE}❯ ${CYAN}govulncheck setup${RESET}"
	cd /workspace
	cp /app/backend/go.mod /app/backend/go.sum .
	go mod download

	echo -e "${BLUE}❯ ${CYAN}govulncheck testing${RESET}"
	govulncheck ./...
	rm -rf /workspace

	echo -e "${BLUE}❯ ${CYAN}Testing backend code${RESET}"
	cd /app/backend
	[ -z "$(go tool fix -diff ./internal)" ]
	go test -json -cover -coverprofile="/tmp/coverage.out" ./... | tparse
	mkdir -p "$DIR/../../test/results/html-reports" "$DIR/../../test/results/junit"
	go tool cover -html="/tmp/coverage.out" -o "$DIR/../../test/results/html-reports/backend-coverage.html"
	go test -v -tags="unit integration" -covermode=atomic ./internal/... 2>&1 | go-junit-report -set-exit-code > "$DIR/../../test/results/junit/backend.xml"
	go-test-coverage -c .testcoverage.yml --p "/tmp/coverage.out"
	# disabled as it can't handle -buildvcs=false flag and complains about it:
	# golangci-lint -v run ./...
else
	# run this script from within docker
	docker pull "${IMAGE}"
	docker run --rm \
		-e BUILD_COMMIT="${BUILD_COMMIT:-notset}" \
		-e BUILD_DATE="$BUILD_DATE" \
		-e BUILD_VERSION="$BUILD_VERSION" \
		-e GOARCH="${2}" \
		-e GOOS="${1}" \
		-e GOPRIVATE="${GOPRIVATE:-}" \
		-e GOPROXY="${GOPROXY:-}" \
		-e NOW="$NOW" \
		-e TZ="${TZ:-Australia/Brisbane}" \
		-v "$(pwd):/app" \
		-w '/app/backend' \
		"${IMAGE}" \
		/app/scripts/ci/test-backend --inside-docker
fi

echo -e "${BLUE}❯ ${GREEN}test-backend ${YELLOW}${1:-} ${GREEN}completed${RESET}"
exit 0
