#!/bin/bash

# Target directory inside the project
TARGET_DIR="src/main/resources/mathjax"

case "$1" in
  --versionOnline)
    # returns the newest version available online 
    npm view mathjax version
    ;;

  --versionInstall)
    # expected to be invoked with a version 
    VERSION_TO_INSTALL="$2"
    if [ -z "$VERSION_TO_INSTALL" ]; then
      echo "Error: Missing version number for --versionInstall."
      exit 1
    fi

    # find out whether installed and if so the version installed. 
    if [ -f "$TARGET_DIR/version.txt" ]; then
      # Here, mathjax is installed, get the version 
      VERSION_INSTALLED=$(cat "$TARGET_DIR/version.txt")
    else
      # Here, mathjax is not installed, get a dummy version. 
      VERSION_INSTALLED="0.0.0"
    fi

    if [ "$VERSION_TO_INSTALL" != "$VERSION_INSTALLED" ]; then
      # Here, we need to install 
        
      # ensure empty folder TARGET_DIR
      rm -rf "$TARGET_DIR"
      mkdir -p "$TARGET_DIR"
        
      # Install mathjax in given version version
      npm install "mathjax@$VERSION_TO_INSTALL" --prefix "$TARGET_DIR" --no-save
        
      # Write version marker
      echo "$VERSION_TO_INSTALL" > "$TARGET_DIR/version.txt"
    fi
    ;;

  *)
    echo "Usage: ./mathjaxConf {--versionOnline|--versionInstall <version>}"
    exit 1
    ;;
esac