#!/bin/bash

set -x

GO_VERSION="1.22.0"
NODE_VERSION="20.5.1"


ARCH="{{ .chezmoi.arch }}"
OSTYPE="{{ .chezmoi.os }}"

if [ ! -d "$HOME/apps" ]; then 
  if ! mkdir -p "$HOME/apps" ; then 
    >&2 echo "make directory failed"
    exit 1
  fi
fi

function install_golang {
  #if command -v go ; then 
  #  return 0
  #fi

  local tmpDir=$(mktemp -d)
  local url="https://go.dev/dl/go$GO_VERSION.$OSTYPE-$ARCH.tar.gz"

  # download
  if ! wget -O "$tmpDir/go.tar.gz" "$url"  ; then 
    rm -rf "$tmpDir"
    >&2  echo "download golang binary failed"
    return 1
  fi

  if ! tar zxf "$tmpDir/go.tar.gz" -C "$tmpDir" ;then 
    rm -rf "$tmpDir"
    >&2 echo "untar golang binary failed"
    return 1
  fi

  mv "$tmpDir/go" "$HOME/apps/go-${GO_VERSION}"

  if [ -L "$HOME/apps/go" ]; then 
    #rm -rf `readlink -f "$HOME/apps/go"`
    unlink "$HOME/apps/go"
  fi

  ln -sf "$HOME/apps/go-${GO_VERSION}" "$HOME/apps/go"

  rm -rf "$tmpDir"
}

function install_nodejs {
  #if command -v node ; then 
  #  return 0
  #fi
  local tmpDir=$(mktemp -d)

  local arch=""

  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}-${OSTYPE}-${arch}.tar.xz"

  if ! wget -O "$tmpDir/node.tar.xz" "$url" ; then 
    rm -rf "$tmpDir"
    >&2 echo "download nodejs binary failed"
    return 1 
  fi

  if ! tar xJf "$tmpDir/node.tar.xz" -C "$tmpDir" ; then 
    rm -rf "$tmpDir"
    >&2 echo "untar nodejs binary failed"
    return 1
  fi

  dirs=$(find "$tmpDir" -type d -mindepth 1 -maxdepth 1 -name 'node*')

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

  if [ -L "$HOME/apps/node" ]; then 
    #rm -rf `readlink -f "$HOME/apps/node"`
    unlink "$HOME/apps/node"
  fi

  ln -sf "$HOME/apps/node-v${NODE_VERSION}" "$HOME/apps/node"

  rm -rf "$tmpDir"
}

function install_rust {
  if command -v cargo ; then 
    return 0
  fi
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --profile default -y
}

{{ if .dev.golang }}
  echo "start install golang ${GO_VERSION}..."
  if ! install_golang ; then 
    >&2 echo "install golang failed"
    exit 1
  fi
{{ end }}

{{ if .dev.nodejs }}
  echo "start install nodejs v${NODE_VERSION}..."
  if ! install_nodejs ; then
    >&2 echo "install nodejs failed"
    exit 1
  fi 
{{ end }}

{{ if .dev.rust }}
  echo "start install rust..."
  if ! install_rust ; then 
    >&2 echo "install rust failed"
    exit 1
  fi  
{{ end }}
