#!/usr/bin/env bash

ROOT="$(git rev-parse --show-toplevel)"
DEST="${ROOT}/tools/bin"

fetch() {
  local tool=$1; shift
  local ver=$1; shift

  local ver_cmd=""
  local fetch_cmd=""
  case "$tool" in
    "golangci-lint")
      ver_cmd="${DEST}/golangci-lint --version 2>/dev/null | cut -d\" \" -f4"
      fetch_cmd="curl -sSfL \"https://raw.githubusercontent.com/golangci/golangci-lint/v${ver}/install.sh\" | sh -s -- -b \"${DEST}\" \"v${ver}\""
      ;;
    "goreleaser")
      ver_cmd="${DEST}/goreleaser --version 2>/dev/null | grep version | cut -d' ' -f3"
      fetch_cmd="curl -sSfL https://install.goreleaser.com/github.com/goreleaser/goreleaser.sh | sh -s -- -b \"${DEST}\" -d \"v${ver}\""
      ;;
    "envtest")
      ver_cmd="cat ${DEST}/.envtest_version 2>/dev/null"
      fetch_cmd="(test -f ${DEST}/setup-envtest.sh || curl -sSLo ${DEST}/setup-envtest.sh https://raw.githubusercontent.com/kubernetes-sigs/controller-runtime/v${ver}/hack/setup-envtest.sh) && (source ${DEST}/setup-envtest.sh; fetch_envtest_tools ${DEST}/../) && echo ${ver} > ${DEST}/.envtest_version"
      ;;
    *)
      echo "unknown tool $tool"
      return 1
      ;;
  esac

  if [[ "${ver}" != "$(eval ${ver_cmd})" ]]; then
    echo "${tool} missing or not version '${ver}', downloading..."
	mkdir -p ${DEST}
    eval ${fetch_cmd}
  fi
}

fetch $@
