#!/bin/bash
# bash is required since indirect variable substitution is used.

set -eu

# Keep this in sync with Dockerfile-go-deps. The digests will be different for each
# version and each platform; they can be found in the *.sha256 files alongside the
# executables at ${dep_base_url}.
depversion=0.5.0
dep_base_url="https://github.com/golang/dep/releases/download/v${depversion}/"

cd "$(pwd -P)"

bindir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
rootdir="$( cd $bindir/.. && pwd )"

os=linux
exe=
if [ "$(uname -s)" = "Darwin" ]; then
  os=darwin
elif [ "$(uname -o)" = "Msys" ]; then
  os=windows
  exe=.exe
fi

depbin="${rootdir}/.dep-${depversion}${exe}"
depurl="${dep_base_url}dep-${os}-amd64${exe}"

if [ ! -f "$depbin" ]; then
  tmp=$(mktemp -d -t dep.XXX)
  (
    cd "$tmp"
    curl -L --silent --fail -o depbin "$depurl"
    sha=$(curl -L --silent --fail "${depurl}.sha256" | awk '{ print $1 }')
    (echo "$sha *depbin" | shasum -c -a 256 -p -s -) || {
      echo "Actual digest of $(pwd)/depbin does not match expected digest."
      exit 1
    }
    chmod +x depbin
  )
  mv "$tmp/depbin" "$depbin"
  rm -rf "$tmp"
fi

$depbin "$@"
