#!/bin/bash

set -e

initialCwd=`pwd -P`

apmPath=$0
builtin cd "`dirname "$apmPath"`"
binDir=`basename "$apmPath"`

# Detect node binary name
osName=`uname -s`
if [ "${osName:0:10}" == 'MINGW32_NT' ]; then
  nodeBin="node.exe"
elif [[ $(uname -r) == *-Microsoft ]]; then
  nodeBin="node.exe"
else
  nodeBin="node"
fi

while [ -L "$binDir" ]
do
  binDir=`readlink "$binDir"`
  builtin cd "`dirname "$binDir"`"
  binDir=`basename "$binDir"`
done

binDir=`pwd -P`

maybe_node_gyp_path="$binDir"/../node_modules/.bin/node-gyp
if [ -e "$maybe_node_gyp_path" ]
then
  export npm_config_node_gyp="$maybe_node_gyp_path"
fi

export PYTHON="${binDir}/python-interceptor.sh"

cliPath="$binDir/../lib/cli.js"
if [[ $(uname -r) == *-Microsoft ]]; then
  cliPath="$(echo $cliPath | sed 's/\/mnt\/\([a-z]*\)\(.*\)/\1:\2/')"
  cliPath="${cliPath////\\}"
else
  builtin cd "$initialCwd"
fi

"$binDir/$nodeBin" "$cliPath" "$@"
