#!/bin/sh

XDG_DATA_HOME="${XDG_DATA_HOME:-${HOME%/}/.local/share}"
GOPATH="${XDG_DATA_HOME}"/go

start_time=$(date '+%s')

/bin/ls -1 "${GOPATH}"/bin/ \
    | while read -r bin; do go version -m "${HOME%/}/.local/share/go/bin/${bin}" \
    | grep '^[[:space:]]path' \
    | awk '{ print $2 }' \
    | grep '^github.com' \
    | sort \
    | uniq \
    | xargs -I{} go install {}@latest; done
    printf "\nGo tools updated ...\n"


if is-linux; then
  go_update() {
    cd "${GOPATH}/src/$1" && git reset --hard HEAD && git clean -fx && cd - || echo "$1 doesn't seem to be installed yet."
    # verbose output is sent to stderr for some reason
    go get -u -v "$*" 2>&1
  }

#  go_update_static() {
#    # shellcheck disable=SC2034 # CGO_ENABLED is in fact used by cmd/go.
#    GOOS=linux GOARCH=arm64 CGO_ENABLED=0 GOFLAGS="$GOFLAGS -buildmode=pie -tags=osusergo,netgo,static_build" go_update "$*"
#  }
#
#  go_install_static() {
#    # shellcheck disable=SC2034 # CGO_ENABLED is in fact used by cmd/go.
#    GOOS=linux GOARCH=arm64 CGO_ENABLED=0 GOFLAGS="$GOFLAGS -buildmode=pie -tags=osusergo,netgo,static_build" go install "$*"
#  }

  go_update "$@"

fi

end_time=$(date '+%s')
elapsed=$(echo "$end_time - $start_time" | bc)
echo "Time elapsed: $elapsed seconds"
