#!/usr/bin/env bash
set -e -o pipefail -u -x

version="$1"

ln -s "/usr/local/go/bin/go" "/usr/local/bin/"
ln -s "/usr/local/go/bin/gofmt" "/usr/local/bin/"

# A stable version of Go 1.4 or newer is required for compiling Go 1.5 and
# newer.
wget -q -O "go.tar.gz" "https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz"
echo "332b64236d30a8805fc8dd8b3a269915b4c507fe  go.tar.gz" | sha1sum --check
mkdir "/usr/local/go-bootstrap"
tar -C "/usr/local/go-bootstrap" -x --strip-components 1 -z -f "go.tar.gz"

# Check out and build a specific version of Go.
git clone "https://github.com/golang/go.git" "/usr/local/go"
# or from upstream "https://go.googlesource.com/go", though gerrit has b/w limits
cd "/usr/local/go"
git checkout "$version"
cd "/usr/local/go/src"
GOROOT_FINAL="/usr/local/go" GOROOT_BOOTSTRAP="/usr/local/go-bootstrap" ./make.bash
