#!/bin/bash

# installs eslint and related plugins in $1

set -e
MYDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

INSTALL_DIR=$1

if [[ -z "$INSTALL_DIR" ]]; then
    echo "Missing an argument.
Usage: $0 directory-to-install-eslint-in">&2
   exit 1
fi

function abspath() { pushd . > /dev/null; if [ -d "$1" ]; then cd "$1"; dirs -l +0; else cd "`dirname \"$1\"`"; cur_dir=`dirs -l +0`; if [ "$cur_dir" == "/" ]; then echo "$cur_dir`basename \"$1\"`"; else echo "$cur_dir/`basename \"$1\"`"; fi; fi; popd > /dev/null; }
INSTALL_DIR=$(abspath "$INSTALL_DIR")

mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"
npm init -y > /dev/null
npm install eslint eslint-plugin-security eslint-plugin-security-node > /dev/null

BIN="${INSTALL_DIR}/node_modules/eslint/bin/eslint.js"
if [ ! -f "${BIN}" ]; then
    echo "ERROR: The installation of eslint completed successfully, but ${BIN} does not exist?!">&2
    exit 1
fi
if [ ! -x "${BIN}" ]; then
    echo "ERROR: The installation of eslint completed successfully, but ${BIN} is not executable?! ">&2
    exit 1
fi

MAIN="${MYDIR}/../../../../build/ts/contrib/tools/eslint/src/eslint.js"
MAIN=$(abspath "$MAIN")
echo "The eslint tool has been installed. Add the fragment below to a config.json file:

{
  ...
  \"tools\": {
    ...

    \"eslint-default\": {
      \"bin\": \"node\",
      \"args\": [ \"${MAIN}\" ],
      \"options\": {
        \"eslintDir\": \"${INSTALL_DIR}\"
      }
    }

    ...
  }
  ...
}"
