#!/bin/sh
#
# gfy - GOARGS... - go(1) fuck yourself | gfy clone PKGNAME
#
# this allows building go projects which have everything vendored
# (or are fetched using "gfy clone") without setting up a GOPATH, just
# run "gfy build" (or "gfy build ./relative/pkg").
#
# only use this tool on the toplevel of a project.

if [ "$1" = clone ]; then
  shift
  dir=${1##*/}

  # shellcheck disable=SC2155
  export GOPATH="${PWD}"/"$(mktemp -d .gfyget.XXXXXX)"
  mkdir -p "${GOPATH}"/pkg
  go get -v -u "$@"
  r="$?"

  mv "${GOPATH}"/src/"$1" "${dir}"
  cd "${dir}" || return
  echo "$1" >"${GOPATH}"/clonename
  mv "${GOPATH}" .gfy
  ln -sfr . .gfy/src/"$1"

  exit "${r}"
fi

mkdir -p .gfy
export GOPATH="${PWD}"/.gfy
mkdir -p "${GOPATH}"/src
mkdir -p "${GOPATH}"/bin
mkdir -p "${GOPATH}"/pkg
pkg=$(cat .gfy/clonename 2>/dev/null \
  || { git remote --verbose 2>/dev/null | awk '/fetch/{ sub(".*://","",$2); sub("com:","com/"); sub("\\.git",""); print $2; quit }' \
    || echo .; })
if [ ! -e "${GOPATH}"/src/"${pkg}" ]; then
  mkdir -p "${GOPATH}"/src/"${pkg}"
  rmdir "${GOPATH}"/src/"${pkg}" 2>/dev/null
  ln -sfr . "${GOPATH}"/src/"${pkg}"
fi
[ -e bin ] || ln -sfr "${GOPATH}"/bin bin

cd "${GOPATH}"/src/"${pkg}" || return
exec go "$@"
