#!/usr/bin/env bash
#
# Golang executor that works with Go's official version management installers.
# Favors Mage for scripts management.
# Supports executing scoped binaries with gomodrun directly for tools stored in root/tools/
#
# Usage:
#   gor mod download
#   gor my-file.go
#   gor mymagescript
#   gor my-local-binary
#   gor --help
#
# ---
# source: https://github.com/dustinblackman/wrappers/blob/master/gor

set -e

walkuptree() {
  DIR=$(pwd)
  while [ -n "${DIR}" ] && [ ! -f "${DIR}/$1" ]; do
    DIR="${DIR%\/*}"
  done

  echo "${DIR}/$1"
}

GO_MOD=$(walkuptree go.mod)
GO_TOOLS=$(walkuptree tools/tools.go)
GO_MAGE=$(walkuptree go.magefile.go)
GO_VERSION=$(awk '/^go / {print $2; exit}' "${GO_MOD}")

# Fails silently if no go tools of package is found.
getToolsPkgNamePath() {
   if [ -z "${GO_TOOLS}" ]; then
     echo ""
     exit 0
   fi

   tools_project_name=$(awk '/^module / {print $2; exit}' "$(dirname "${GO_TOOLS}")/go.mod")
   pkg_name=$(awk -F '"' "/\/$1/ {print \$2; exit}" "${GO_TOOLS}")

   if [ -z "${pkg_name}" ]; then
     echo ""
     exit 0
   fi

  (
    cd "$(dirname "${GO_TOOLS}")"
    go mod graph | awk -v tools_project_name="${tools_project_name}" -v pkg_name="${pkg_name}" '{
      split($2, parts, "@");
      if ($0 ~ tools_project_name && pkg_name ~ parts[1]) {
        split(pkg_name, cmdparts, parts[1]);
        print $2""cmdparts[2];
        exit;
      }
    }'
  )
}

runToolsBin() {
  bin_name="$1"
  shift

  if [ -z "${GO_TOOLS}" ]; then
    >&2 echo "[gor] No tools.go found"
    exit 1
  fi

  pkg_name=$(getToolsPkgNamePath "${bin_name}")
  pkg_name_serialized=$(echo "${pkg_name}" | tr '/@' '_')
  bin_path="$(dirname "${GO_TOOLS}")/.gor/bin/${pkg_name_serialized}/${bin_name}"

  if [ ! -f "${bin_path}" ]; then
    (
        mod_path="$(go env GOPATH)/pkg/mod/${pkg_name}"
        if [ ! -d "${mod_path}" ]; then
          cd "$(dirname "${GO_TOOLS}")"
          go mod download >/dev/null
        fi

        cd "${mod_path}"
        mkdir -p "$(dirname "${bin_path}")"
        GOWORK="off" go build -o "${bin_path}" >/dev/null
    )
  fi

  if [ ! -t 0 ]; then
    cat - | "${bin_path}" "$@"
  else
    "${bin_path}" "$@"
  fi
}

if [ "$1 $2" = "mod init" ]; then
  go "$@"
  exit 0
fi

# If Go is not setup in path correctly, set it here.
GO_BIN_PATH=$(go env GOPATH)/bin
if ! echo "${PATH}" | grep -q "${GO_BIN_PATH}"; then
  export PATH="${GO_BIN_PATH}:${PATH}"
fi

# Download Go version installer
if ! command -v "go${GO_VERSION}" >/dev/null 2>&1; then
  >&2 echo "[gor] Preparing Go version ${GO_VERSION}"
  go install "golang.org/dl/go${GO_VERSION}@latest"
fi

# Download Go version
if ! "go${GO_VERSION}" --help 2>&1 | grep -q 'Go is a tool'; then
  >&2 echo "[gor] Installing Go version ${GO_VERSION}"
  "go${GO_VERSION}" download
fi

# Put the correct Go version at the top of the path.
VERSIONED_GO_ROOT=$("go${GO_VERSION}" env GOROOT)
export PATH="${VERSIONED_GO_ROOT}/bin:${PATH}"
export GOROOT="${VERSIONED_GO_ROOT}"

gocmd=""
is_tools="false"
mage_cleaned_params=$(echo "$1" | tr -dc '[:alpha:]' | awk '{print tolower($1)}')

# if [ "$1" = *.go ]; then
if echo "$1" | grep -q ".go" >/dev/null; then
  gocmd="go run $*"
elif [ "$1" = "--gor-bin-find" ]; then
  gocmd="getToolsPkgNamePath $2"
elif [ "$1" = "gofmt" ]; then
  gocmd="gofmt"
elif awk '/^func / {print $2}' "${GO_MAGE}" 2>/dev/null | awk -F '(' '{print $1}' | awk '{print tolower($1)}' | grep -q "^${mage_cleaned_params}$"; then
  shift
  is_tools="true"
  gocmd="runToolsBin mage ${mage_cleaned_params} $*"
elif [ -n "$(getToolsPkgNamePath "$1")" ]; then
  is_tools="true"
  gocmd="runToolsBin $*"
else
  gocmd="go $*"
fi

# Support passing in stdin.
if [ "${is_tools}" = "false" ] && [ ! -t 0 ]; then
  gocmd="cat - | ${gocmd}"
fi

eval "${gocmd}"
