#!/bin/bash

set -xe

if [ -z "$1" ]; then
    echo "Usage: $0 <node-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_nodejs() {
  local arch=""

  NODE_VERSION=$1

  case "$ARCH" in 
    "amd64")
      arch="x64"
      ;;
    "arm64")
      arch="arm64"
      ;;
    *)
      >&2 echo "arch ($ARCH) not support"
      return 1
      ;;
  esac

  local url="https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-${OS}-${arch}.tar.xz"

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

  if ! tar xf "$TMP_DIR/node.tar.xz" -C "$TMP_DIR"; then
    >&2 echo "Failed to extract $TMP_DIR/node.tar.xz"
    return 1
  fi

  dirs=$(find "$TMP_DIR" -maxdepth 1 -type d -name "node*")

  if [ -z "$dirs" ]; then
    >&2 echo "Failed to find node folder"
    return 1
  fi 

  mv "$dirs" "$HOME/apps/node-v$NODE_VERSION"

  if [ -L "$HOME/apps/node" ]; then
    unlink "$HOME/apps/node"
  fi

  ln -s "$HOME/apps/node-v$NODE_VERSION" "$HOME/apps/node"

  return 0
}

install_require_dep() {
  PATH="$HOME/apps/go/bin:$HOME/apps/node/bin:$PATH"

  if command -v npm > /dev/null; then 
    npm i -g typescript typescript-language-server dockerfile-language-server-nodejs svelte-language-server
  fi
}
install_nodejs "$1"
install_require_dep
