#!/usr/bin/env bash

set -eu

NAME="ignition"
ORG_PATH="github.com/coreos"
REPO_PATH="${ORG_PATH}/${NAME}"
GLDFLAGS=${GLDFLAGS:-}

if [ -z ${VERSION+a} ]; then
	echo "Using version from git..."
	VERSION=$(git describe --dirty --always)
fi

GLDFLAGS+="-X github.com/coreos/ignition/internal/version.Raw=${VERSION}"

if [ ! -h gopath/src/${REPO_PATH} ]; then
	mkdir -p gopath/src/${ORG_PATH}
	ln -s ../../../.. gopath/src/${REPO_PATH} || exit 255
fi

eval $(go env)

if [ -z ${BIN_PATH+a} ]; then
	export BIN_PATH=${PWD}/bin/${GOARCH}
fi

export GOPATH=${PWD}/gopath
export CGO_ENABLED=1

echo "Building ${NAME}..."
# clean the cache since cgo isn't correctly handled by gocache. Test to see if this version
# of go supports caching before trying to clear the cache
go clean -help 2>&1 | grep -F '[-cache]' >/dev/null && go clean -cache -testcache internal
go build -buildmode=pie -ldflags "${GLDFLAGS}" -o ${BIN_PATH}/${NAME} ${REPO_PATH}/internal

NAME="ignition-validate"

echo "Building ${NAME}..."
go build -ldflags "${GLDFLAGS}" -o ${BIN_PATH}/${NAME} ${REPO_PATH}/validate
