#!/usr/bin/env bash
#
# getgo - Install latest go(lang)
# dependencies: wget sudo tar coreutils(mktemp mv rm tail)
#
# Usage: getgo [<version>]
#
# when TMPDIR is set, it is used for the temporary directory

# shellcheck shell=bash disable=SC2312

set +vx

# install location for the go tree
goloc=/usr/local

abort() { # $1:message
  echo "ABORT: $1"
  exit 1
}

# doas() { # $1:prompt $2..:command
#   prompt="Privileges required" sudo=
#   [ -n "$1" ] && prompt+=" $1:" || prompt+=':'
#   shift
#   ((EUID)) && ! sudo=$(type -p sudo) \
#     && abort "privileges required but 'sudo' not available"
#   ${sudo} -nv &>/dev/null || echo "${prompt}"
#   ${sudo} "$@"
# }

ver="$1"
[ -n "${ver//[.0-9]/}" ] \
  && abort "Version should only contain numbers and a dot, not: ${ver}"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
arch="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')"
# os=${GO_OS:-Linux} os="${os,,}"
# [[ $(uname -m) = armv7l ]] && arch=armv6l || arch=amd64

: "${arch:=${GO_ARCH}}"
: "${ver:=${GO_VERSION}}"

[ -z "${ver}" ] \
  && url=$(wget -qO- "https://golang.org/dl" | grep -o "[^\"]*\.${os}-${arch}\.tar\.gz" | head -1) \
  && ver=${url%."${os}"-"${arch}".tar.gz} ver=${ver#/dl/go}

# use the discovered or specified $ver
dl="go${ver}.${os}-${arch}.tar.gz"
url="https://golang.org/dl/${dl}"
echo "Installing go ${ver} on ${arch} ${os}"

tmp=$(mktemp -d --tmpdir="${TMPDIR}")
trap "doas 'to cleanup'" rm -rf -- "${tmp}" QUIT EXIT
wget -qO "${tmp}/${dl}" "${url}" || abort "could not download go"
tar xf "${tmp}/${dl}" -C "${tmp}" || abort "error unpacking ${dl} to ${tmp}"
doas 'to make root' chown root:root -R -- "${tmp}"

# move install directory if it exists already
if [ -d "${goloc}/go" ]; then
  doas 'to move old go directory' mv -v -- "${goloc}/go" \
    "${goloc}/$("${goloc}"/go/bin/go version | cut -f3 -d' ')_old${RANDOM}" \
    || abort "could not move ${goloc}/go out of the way"
fi
doas 'to install go directory' mv -v -- "${tmp}/go" "${goloc}" \
  || abort "could not move ${tmp}/go to ${goloc}"

a="p='${goloc}/go/bin' && [[ :\${PATH}: != *:\${p}:* ]] && export PATH=\${p}:\${PATH}"
[ -n "${GOROOT}" ] || a+="\nexport GOROOT='${goloc}/go'"
[ -n "${GOBIN}" ] || a+="\nexport GOBIN=\${HOME}/go/bin"
echo "Right now: GOROOT=${GOROOT} GOBIN=${GOBIN} PATH=${PATH}"
export GOROOT="${goloc}/go" GOPATH=~/go
printf '%b\n' "Add to ~/.bashrc:\n\n${a}"
eval "${a//\\n/;}"

exit 0
