#!/bin/bash
if [[ "$OSTYPE" == "darwin"* ]]; then
  PYTHON="python"
  python -c "" &>/dev/null
  if [[ "$?" != "0" ]]; then
    PYTHON="python3"
    python3 -c "" &>/dev/null
  fi
  if [[ "$?" != "0" ]]; then
    PYTHON="python2"
    python2 -c "" &>/dev/null
  fi
  SOURCE=`${PYTHON} -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "${BASH_SOURCE[0]}"`
  EXECUTION_DIR=`${PYTHON} -c 'import os, sys; print(os.path.dirname(os.path.realpath(sys.argv[1])))' "${BASH_SOURCE[0]}"`
  NODE_PATH="./node_modules:${EXECUTION_DIR}:${EXECUTION_DIR}/node_modules"
  export NODE_PATH="${NODE_PATH}"
else
  SOURCE="${BASH_SOURCE[0]}"
  while [ -h "$SOURCE" ]; do
    DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
  done
  EXECUTION_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"

  APP_FCFNODE_PATH=`which fcfnode`
  APP_NODE_PATH=`which node`
  if [[ -z "${APP_FCFNODE_PATH}" || -z "${APP_NODE_PATH}" ]]; then
    if [ -f "/etc/bash.bashrc" ]; then
      source "/etc/bash.bashrc"
    fi
    USER_BASHRC_PATH=`realpath ~/.bashrc`
    if [ -f "${USER_BASHRC_PATH}" ]; then
      source "${USER_BASHRC_PATH}"
    fi
  fi

  if [ -z "${NODE_PATH}" ]; then
    NODE_PATH="./node_modules:${EXECUTION_DIR}:${EXECUTION_DIR}/node_modules"
  else
    NODE_PATH="./node_modules:${EXECUTION_DIR}:${EXECUTION_DIR}/node_modules:${NODE_PATH}"
  fi
  export NODE_PATH="${NODE_PATH}"
fi
node "$@"
