#!/bin/bash

set -ex 

if [ -z "$1" ]; then
    echo "Usage: $0 <go-version>"
    exit 1
fi

# chezmoi will replace the OS and ARCH variables
ARCH="{{ .chezmoi.arch }}"
OS="{{ .chezmoi.os }}"

if [ ! -d "$HOME/apps" ]; then
  if ! mkdir -p "$HOME/apps"; then
    >&2 echo "Failed to create $HOME/apps"
    exit 1
  fi
fi

deleteTmpDir() {
  if [ -d "$1" ]; then
    rm -rf "$1"
  fi
}

TMP_DIR=$(mktemp -d)

trap 'deleteTmpDir '"$TMP_DIR"'' EXIT

install_go() {

  local url="https://go.dev/dl/go$1.$OS-$ARCH.tar.gz"

  if ! wget -O "$TMP_DIR/go.tar.gz" "$url"; then
    >&2 echo "Failed to download $url"
    return 1
  fi

  if ! tar zxf "$TMP_DIR/go.tar.gz" -C "$TMP_DIR"; then 
    >&2 echo "Failed to extract $TMP_DIR/go.tar.gz"
    return 1
  fi

  mv "$TMP_DIR/go" "$HOME/apps/go-$1"

  # relink go folder to the new version 
  if [ -L "$HOME/apps/go" ]; then
    unlink "$HOME/apps/go"
  fi

  ln -s "$HOME/apps/go-$1" "$HOME/apps/go"

  return 0
}

install_go "$1"
