#!/usr/bin/env bash
set -euo pipefail

pushd "$(dirname "$0")/.." >/dev/null

cloud=${DBAAS_CLOUD:-""}
build_tags=
if ! [[ -z $cloud ]] ; then
	build_tags="$cloud"
fi

runtime=${DBAAS_RUNTIME:-""}
if ! [[ -z $runtime ]] ; then
	if [[ -z $build_tags ]] ; then
		build_tags="$runtime"
	else
		build_tags="${build_tags} $runtime"
	fi
fi

# The ldflags strip dwarf info for debuggers, but we still get the stack trace
goargs=( "-ldflags=-s -w " )
#
if git rev-parse --git-dir > /dev/null 2>&1; then
    goargs+=( "-ldflags= -X 'github.com/tidbcloud/core-svc/pkg/version.GitHash=$(git rev-parse HEAD)'" )
fi
if ! [[ -z $build_tags ]] ; then
	goargs+=( "--tags=$build_tags" )
fi

GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build "${goargs[@]}" "$@"
# We can support building in docker if someone wants to use this
# Currently nobody does. I have noticed it can be significantly slower
#if ! command -v go 1>/dev/null; then
#	DOCKER_DIR="/go/src/github.com/tidbcloud/core-svc"
#	docker run --rm -it -e "GOPATH=/go" -e GO111MODULE=on -e CGO_ENABLED=0 -e GOOS=linux -e GOARCH=amd64 -w "$DOCKER_DIR/$(basename "$PWD")" -v "$(dirname "$(pwd)"):$DOCKER_DIR" golang:1.13.1-alpine go build  "${goargs[@]}" "$@"
#fi
