#!/bin/bash

#
# ci/scripts/shipit
#
# Script for generating Github release / tag assets
# and managing release notes for a software pipeline
#
# author:  James Hunt <james@niftylogic.com>
# created: 2016-03-30
# testing line

set -eu

: ${GIT_EMAIL:?required}
: ${GIT_NAME:?required}

if [[ -z ${VERSION_FROM} ]]; then
  echo >&2 "VERSION_FROM environment variable not set, or empty.  Did you misconfigure Concourse?"
  exit 2
fi
if [[ ! -f ${VERSION_FROM} ]]; then
  echo >&2 "Version file (${VERSION_FROM}) not found.  Did you misconfigure Concourse?"
  exit 2
fi
VERSION=$(cat ${VERSION_FROM})
if [[ -z ${VERSION} ]]; then
  echo >&2 "Version file (${VERSION_FROM}) was empty.  Did you misconfigure Concourse?"
  exit 2
fi

if [[ ! -f ${REPO_ROOT}/ci/release_notes.md ]]; then
  echo >&2 "ci/release_notes.md not found.  Did you forget to write them?"
  exit 1
fi

###############################################################

#?#ORIGIN=$(pwd)
TARGETS=${TARGETS:-linux/amd64 darwin/amd64}
ROOT=$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )

pushd $REPO_ROOT
newgopath=${ROOT%%/gopath/*}/gopath
if [[ -d ${newgopath} ]]; then
	if [[ -z ${GOPATH} ]]; then
		GOPATH="${newgopath}"
	else
		GOPATH="${newgopath}:${GOPATH}"
	fi
	PATH="${PATH}:${newgopath}/bin"
fi
echo ">> Using GOPATH ${GOPATH}"
go get github.com/mitchellh/gox
popd

if [[ -n ${STATIC_BINARY} && ${STATIC_BINARY} != "false" ]]; then
	export CGO_ENABLED=0
fi

pushd $REPO_ROOT
mkdir artifacts
gox -osarch="${TARGETS}" --output="artifacts/${BINARY}-{{.OS}}-{{.Arch}}" -ldflags="-X main.Version=${VERSION}" ./...
go build -o "${BINARY}" -ldflags="-X main.Version=${VERSION}" ${CMD_PKG:-.}
./${BINARY} -v
popd

echo "v${VERSION}"                         > ${RELEASE_ROOT}/tag
echo "${RELEASE_NAME} v${VERSION}"         > ${RELEASE_ROOT}/name
mv ${REPO_ROOT}/ci/release_notes.md          ${RELEASE_ROOT}/notes.md
mv ${REPO_ROOT}/artifacts                    ${RELEASE_ROOT}/artifacts

cat > ${RELEASE_ROOT}/notification <<EOF
<!here> New ${RELEASE_NAME} v${VERSION} released!
EOF


# GIT!
if [[ -z $(git config --global user.email) ]]; then
  git config --global user.email "${GIT_EMAIL}"
fi
if [[ -z $(git config --global user.name) ]]; then
  git config --global user.name "${GIT_NAME}"
fi

(cd ${REPO_ROOT}
 git merge --no-edit ${BRANCH}
 git add -A
 git status
 git commit -m "release v${VERSION}")

# so that future steps in the pipeline can push our changes
cp -a ${REPO_ROOT} ${REPO_OUT}/git
