#!/usr/bin/env bash
set -e

# a helper to provide ".exe" when it's appropriate
binary_extension() {
	if [ "$(go env GOOS)" = 'windows' ]; then
		echo -n '.exe'
	fi
}

GO_PACKAGE='github.com/docker/docker/cmd/dockerd'
BINARY_SHORT_NAME='dockerd'
BINARY_NAME="$BINARY_SHORT_NAME-$VERSION"
BINARY_EXTENSION="$(binary_extension)"
BINARY_FULLNAME="$BINARY_NAME$BINARY_EXTENSION"

source "${MAKEDIR}/.go-autogen"

hash_files() {
	while [ $# -gt 0 ]; do
		f="$1"
		shift
		dir="$(dirname "$f")"
		base="$(basename "$f")"
		for hashAlgo in md5 sha256; do
			if command -v "${hashAlgo}sum" &> /dev/null; then
				(
					# subshell and cd so that we get output files like:
					#   $HASH docker-$VERSION
					# instead of:
					#   $HASH /go/src/github.com/.../$VERSION/binary/docker-$VERSION
					cd "$dir"
					"${hashAlgo}sum" "$base" > "$base.$hashAlgo"
				)
			fi
		done
	done
}

(
export GOGC=${DOCKER_BUILD_GOGC:-1000}

if [ "$(go env GOOS)/$(go env GOARCH)" != "$(go env GOHOSTOS)/$(go env GOHOSTARCH)" ]; then
	# must be cross-compiling!
	case "$(go env GOOS)/$(go env GOARCH)" in
		windows/amd64)
			export CC=x86_64-w64-mingw32-gcc
			export CGO_ENABLED=1
			;;
		linux/arm)
			case "${GOARM}" in
			5|"")
				export CC=arm-linux-gnueabi-gcc
				export CGO_ENABLED=1
				;;
			7)
				export CC=arm-linux-gnueabihf-gcc
				export CGO_ENABLED=1
				;;
			esac
			;;
		linux/arm64)
			export CC=aarch64-linux-gnu-gcc
			export CGO_ENABLED=1
			;;
		linux/amd64)
			export CC=x86_64-linux-gnu-gcc
			export CGO_ENABLED=1
			;;
	esac
fi

# -buildmode=pie is not supported on Windows and Linux on mips.
case "$(go env GOOS)/$(go env GOARCH)" in
	windows/*|linux/mips*)
		;;
	*)
		BUILDFLAGS+=( "-buildmode=pie" )
		;;
esac

echo "Building: $DEST/$BINARY_FULLNAME"
echo "GOOS=\"${GOOS}\" GOARCH=\"${GOARCH}\" GOARM=\"${GOARM}\""
go build \
	-o "$DEST/$BINARY_FULLNAME" \
	"${BUILDFLAGS[@]}" \
	-ldflags "
		$LDFLAGS
		$LDFLAGS_STATIC_DOCKER
		$DOCKER_LDFLAGS
	" \
	${GO_PACKAGE}
)

echo "Created binary: $DEST/$BINARY_FULLNAME"
ln -sf "$BINARY_FULLNAME" "$DEST/$BINARY_SHORT_NAME$BINARY_EXTENSION"

hash_files "$DEST/$BINARY_FULLNAME"