#!/bin/sh

# The checksums below must correspond to the downloads for this version.
GO_VERSION=go1.9.2

if [ $(uname -s) = "Darwin" ]; then
    GO_PKG=${GO_VERSION}.darwin-amd64.tar.gz
    GO_PKG_SHA=8b4f6ae6deae1150d2e341d02c247fd18a99af387516540eeb84702ffd76d3a1
elif [ $(uname -s) = "Linux" ]; then
    GO_PKG=${GO_VERSION}.linux-amd64.tar.gz
    GO_PKG_SHA=de874549d9a8d8d8062be05808509c09a88a248e77ec14eb77453530829ac02b
else
    echo 1>&2 "I don't know how to install Go on your platform."
    echo 1>&2 "Please install $GO_VERSION or later and add it to your PATH."
    exit 1
fi

archivesum() {
    shasum -a256 "$ARCHIVE"
}

archiveok() {
    test -f "$ARCHIVE" && archivesum | grep -q $GO_PKG_SHA
}

if go version 2>/dev/null | grep -q $GO_VERSION; then
    go version
    exit 0
fi

ROOTDIR="$( cd "$( dirname "$0" )/.." && pwd )"
VENDORDIR="$ROOTDIR/vendor"
DOWNLOAD_URL=https://storage.googleapis.com/golang/$GO_PKG
ARCHIVE="$VENDORDIR/$GO_PKG"
INSTALLDIR="$VENDORDIR/$GO_VERSION"
export GOROOT="$INSTALLDIR/go"
INSTALLEDGO="$GOROOT/bin/go"

if [ -x $INSTALLEDGO ]; then
    "$INSTALLEDGO" version
    exit 0
fi

if ! archiveok; then
    echo "Downloading $DOWNLOAD_URL"
    mkdir -p "$VENDORDIR"
    if ! curl -L -o "$ARCHIVE" $DOWNLOAD_URL; then
        rm -f "$ARCHIVE"
        echo 1>&2 "download failed"
    fi
    if ! archiveok; then
        archivesum 1>&2
        echo 1>&2 "expected checksum $GO_PKG_SHA"
        exit 1
    fi
fi

rm -rf "$INSTALLDIR"
mkdir -p "$INSTALLDIR"
tar xf "$ARCHIVE" -C "$INSTALLDIR"
"$INSTALLEDGO" version
