#!/usr/bin/env bash
# shellcheck disable=SC2016

source "$SHELLOPS_DIR/plugins/tools/common.sh"

version="$(__shellops__tool_version go)"

if command -v go >/dev/null 2>&1 && go version | grep -q "go${version} "; then
  export PATH="/usr/local/go/bin:$PATH"
  export PATH="${HOME}/go/bin:$PATH"
  shell_rc_offer_line \
    "Go toolchain and go install binaries" \
    'export PATH="$HOME/go/bin:/usr/local/go/bin:$PATH"'
  return 0
fi

platform="$(xplat_os)"
arch="$(xplat_arch)"
archive="go${version}.${platform}-${arch}.tar.gz"
tmpdir="$(mktemp -d)"

curl -fsSL "https://go.dev/dl/${archive}" -o "$tmpdir/$archive"
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf "$tmpdir/$archive"
rm -rf "$tmpdir"

export PATH="/usr/local/go/bin:$PATH"
export PATH="${HOME}/go/bin:$PATH"
shell_rc_offer_line \
  "Go toolchain and go install binaries" \
  'export PATH="$HOME/go/bin:/usr/local/go/bin:$PATH"'
