#!/usr/bin/env bash

# http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in
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 )"

# Had to remove this so that we could just use one command `esy` which we
# forward everything to.
# We'll have to reimplement v that feature in the actual js impl.
# CURDIR=`pwd`
# while [ ! -e "$CURDIR/package.json" ]; do
#     if [ "$CURDIR" == "/" ]; then
#         echo "Cannot find package.json" >&2
#         exit 1
#     fi
#     CURDIR=`cd $CURDIR/..; pwd`
# done


# Capture the error output
# Capturing stderr is very important to prevent nodejs from setting
# stderr to nonblocking mode

EJECT_PATH="$PWD/node_modules/.cache/esy"

EJECT_MAKEFILE="
eject: $EJECT_PATH
$EJECT_PATH: $PWD/package.json \$(shell find $PWD/node_modules -name 'package.json')
	rm -rf \$(@)
	mkdir -p \$(@D)
	/usr/bin/env node $SCRIPTDIR/esy.js build-eject \$(@)
"

builtInEject () {
  make -s -f <(echo "$EJECT_MAKEFILE") eject
}

if [ "$1" == "build" ] || [ "$1" == "shell" ] || [ "$1" == "clean" ]; then
  EJECT_LOG=`builtInEject 2>&1`
  if [ $? -ne 0 ]; then
    echo "Failed prepare build environment:"
    printf "%s\n" "$EJECT_LOG" >&2
    exit 1
  fi
  make -j -s -f "$EJECT_PATH/Makefile" "$1"

elif [ "$1" == "build-eject" ]; then
  builtInEject

elif [ "$1" == "install" ]; then
	/usr/bin/env node $SCRIPTDIR/esy.js install $@

else
  SETENVCMD=$(/usr/bin/env node $SCRIPTDIR/esy.js 2>&1)
  if [ $? -ne 0 ]; then
    echo "Failed to get environment:"
    printf "%s\n" "$SETENVCMD" >&2
    exit 1
  fi

  if [ -z "${ESY__SANDBOX+x}" ]; then
    export ESY__SANDBOX="$PWD"
  fi
  if [ -z "${ESY__STORE+x}" ]; then
    export ESY__STORE="$HOME/.esy"
  fi

  if [ "$1" != "" ]; then
    eval "$SETENVCMD"
    exec "$@"
  else
    echo "$SETENVCMD"
  fi
fi
