#!/bin/bash
f="/tmp/$$-command.hst"
# we install via pip so the python we use is, resolve $SOURCE until the file is no longer a symlink
# so one can symlink to /usr/local/bin etc...
# stolen from https://github.com/facebook/PathPicker/blob/master/fpp
SOURCE=$0
# resolve $SOURCE until the file is no longer a symlink
while [ -h "$SOURCE" ]; do
  BASEDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  # if $SOURCE was a relative symlink, we need to resolve it relative to
  # the path where the symlink file was located
  [[ $SOURCE != /* ]] && SOURCE="$BASEDIR/$SOURCE"
done
BASEDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
# if its installed globally we cant use e relative path to this script so
# we use python
PYTHON=$BASEDIR/python

if [ ! -f "$PYTHON" ]; then
    PYTHON="python"
    # if we are under virtualenv and hst is installed in system libraries,
    # we need to use systems python.
    if [ ! -z "$VIRTUAL_ENV" ]; then
        # echo "in virtual env but hst is installed globally"
        # hoping this is the correct python
        PYTHON="$(which -a python | tail -n 1)"
        # echo $PYTHON
    fi

fi

hstpy="$($PYTHON -c 'from hst import hst; print hst.__file__.replace(".pyc", ".py")')"
$PYTHON $hstpy --out=$f "$@"
if [[ $? != 0 ]]; then exit $?; fi
if [ -f "$f" ]
then
    #cat $f
    $SHELL -i $f < /dev/tty
fi