#!/bin/bash

printError() {
  echo >&2 "ERROR:";
  echo >&2 "$0 command is not installed correctly. ";
  TROUBLESHOOTING="When installing <package_name>, did you see any errors in the log? "
  TROUBLESHOOTING="$TROUBLESHOOTING - What does (which <binary_name>) return? "
  TROUBLESHOOTING="$TROUBLESHOOTING - Please file a github issue on <package_name>'s repo."
  echo >&2 "$TROUBLESHOOTING";
}

if [ -z ${REASON_hCLI__ENVIRONMENTSOURCED__REASON_hCLI_hESY_hSANDBOX+x} ]; then
  if [ -z ${REASON_hCLI__ENVIRONMENTSOURCED+x} ]; then
    
#
# Define $SCRIPTDIR
#

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$SCRIPTDIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

    esyReleasePackageRoot=$(dirname "$SCRIPTDIR")
    export ESY_EJECT__PREFIX="$esyReleasePackageRoot"
    esySandboxEnv="$esyReleasePackageRoot/r/build-eject/sandbox-env"
    source "$esySandboxEnv"
    export REASON_hCLI__ENVIRONMENTSOURCED="sourced"
    export REASON_hCLI__ENVIRONMENTSOURCED__REASON_hCLI_hESY_hSANDBOX="sourced"
  fi
  command -v $0 >/dev/null 2>&1 || {
    printError;
    exit 1;
  }
  if [[ "$1" == ""  ]]; then
  cat << EOF

Welcome to reason-cli

The following commands are available: ocamlmerlin, ocamlmerlin-reason, rtop, utop, refmt, refmttype, reopt, rebuild, reactjs_jsx_ppx_v2, reactjs_jsx_ppx_v3, reason-cli-esy-sandbox

Note:

- reason-cli-esy-sandbox bash

  Starts a sandboxed bash shell with access to the reason-cli environment.

  Running builds and scripts from within "reason-cli-esy-sandbox bash" will typically increase
  the performance as environment is already sourced.

- <command name> ----where

  Prints the location of <command name>

  Example: ocaml ----where

EOF
else
  if [ "$1" == "bash" ]; then
    # Important to pass --noprofile, and --rcfile so that the user's
    # .bashrc doesn't run and the npm global packages don't get put in front
    # of the already constructed PATH.
    bash --noprofile --rcfile <(echo 'export PS1="[reason-cli sandbox] "')
  else
    echo "Invalid argument $1, type reason-cli-esy-sandbox for help"
  fi
fi
else
  printError;
  exit 1;
fi
