#!/bin/bash
GREEN='\033[1;32m'
BLUE='\033[1;34m'
NC='\033[0m' # No Color
DATE_FORMAT='+%Y-%m-%d %H:%M:%S.%3N'

function success {
  echo -e "[$(date "${DATE_FORMAT}")] ${GREEN}$1${NC}"
}

function info {
  echo -e "[$(date "${DATE_FORMAT}")] ${BLUE}$1${NC}"
}

set -e

mkdir -p ~/nexus-tools

wget -q --show-progress https://gitlab.nexdev.uk/nexus-mods/public/nexus-tools/-/raw/master/run.sh -O ~/nexus-tools/nexus-tools.sh
wget -q --show-progress https://gitlab.nexdev.uk/nexus-mods/public/nexus-tools/-/raw/master/NEXUS_TOOLS_VERSION -O ~/nexus-tools/VERSION

chmod +x ~/nexus-tools/nexus-tools.sh

# Remove alias from old .bashrc location, prefer aliases file.
sed -i '/^alias nexus/d' "$HOME/.bashrc"

shopt -s expand_aliases
TOOLS_ALIAS="alias nexus=\"~/nexus-tools/nexus-tools.sh\""
ALIASES_FILE="$HOME/.bash_aliases"
if [[ ! -f "$ALIASES_FILE" ]]; then
  touch "$ALIASES_FILE"
fi
source $ALIASES_FILE

TOOLS_INSTALLED=
if [[ "$(type -t nexus)" == "alias" ]]; then
  # alias exists, check whether it needs updating.
  INSTALLED_TOOLS_ALIAS=$(cat $ALIASES_FILE | grep "^alias nexus" | tail -n1)
  if [[ "$INSTALLED_TOOLS_ALIAS" == "$TOOLS_ALIAS" ]]; then
    TOOLS_INSTALLED=true
  else
    info "removing old alias.."
    sed -i '/^alias nexus/d' $ALIASES_FILE
  fi
fi
if [[ "$TOOLS_INSTALLED" == "true" ]]; then
  success "nexus alias already installed and up to date."
else
  info "installing nexus alias.."
  echo "$TOOLS_ALIAS" >>"$ALIASES_FILE"
  source $ALIASES_FILE
fi

info "Tools ready. Existing shells will need to source $ALIASES_FILE"
