#!/bin/bash
OS=$(uname)
# Find original directory of bash script, resovling symlinks
# http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
bin_dir="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
install_dir=$(dirname "$bin_dir")

lib_dir=$install_dir/lib
libexec_dir=$install_dir/libexec

commands="driver util plot fqidx rcat"
if [ "$#" -eq 0 ]; then
    str=`echo $commands | tr -s " " ","`
    echo "Thank you for using Sentieon software. sentieon supported commands are $str" 
    exit 1
fi
fun=$1
shift
found="no"
for f in $commands
do
    if [ "x$f" = "x$fun" ]; then
        found="yes"
    fi
done
if [ "$found" = "no" ]; then
    echo "sentieon command $fun not found"
    exit 1
fi
cmd="$libexec_dir/$fun"
# restart local lic server if needed
if [ "$#" -gt 1 -a -e "$SENTIEON_LICENSE" ]; then
    licsrvr="$libexec_dir/licsrvr"
    #check if license is localhost or 127.0.0.1
    grep -q '^MachineID: *localhost:[0-9]*' $SENTIEON_LICENSE
    if [ $? -eq 0 ]; then
        timeout=0
        #check if licsrvr is running
        while ! $licsrvr --ping $SENTIEON_LICENSE 2>/dev/null; do
            $licsrvr --start --log licsrvr.log --linger 300 $SENTIEON_LICENSE
            sleep 1
            timeout=$(($timeout+1))
            if [ $timeout -eq 30 ]; then
                echo "License server could not be started" >&2
                echo "Please check licsrvr.log for more information" >&2
                exit 2
            fi
        done
    fi
fi

case "$OS" in
Darwin)
    DYLD_LIBRAR_PATH=${DYLD_LIBRAR_PATH:+$DYLD_LIBRAR_PATH:}${lib_dir}
    export DYLD_LIBRARY_PATH
    ;;
CYGWIN*)
    PATH=${PATH:+$PATH:}${lib_dir}
    export PATH
    ;;
*)
    # detect libpython2.7.so path
    for prog in ${SENTIEON_PYTHON:-python2 python}; do
        pylib=$($prog -c "
import os
import sys
from distutils import sysconfig

v = sys.hexversion >> 16
if v >= 0x0207 and v < 0x0300:
    pylib = None
    for libdir in sysconfig.get_config_vars('LIBDIR') or [ sys.exec_prefix ]:
        for parent, dirs, files in os.walk(libdir):
            if 'libpython2.7.so.1.0' in files:
                pylib = parent
                break
        if pylib:
            print pylib
            break
        ")
        [ $? -ne 0 ] && continue
        [ "$pylib" ] && break
    done
    LD_LIBRARY_PATH=${lib_dir}:${LD_LIBRARY_PATH##:}
    LD_LIBRARY_PATH=${pylib}:${LD_LIBRARY_PATH##:}
    LD_LIBRARY_PATH=${LD_LIBRARY_PATH##:} # remove leading :
    LD_LIBRARY_PATH=${LD_LIBRARY_PATH%%:} # remove trailing :
    export LD_LIBRARY_PATH
    ;;
esac

exec $cmd "$@"
