#!/bin/bash

usage(){
    cat <<- end
usage: `basename $0` [-setcookie <cookie>] [-nocookie] [-nettick <tick>]
       [-pa <path>] [-win] [-dbg] [-vsn <OTP version>] [-proxy proxy] [node]
end
    exit
}

if [ ${0:0:1} == "/" ];then
    SPATH=$0
elif [ -x $PWD/$0 ];then
    SPATH=$PWD/$0
else
    SPATH=`which $0`
fi

if [ -L $SPATH ];then
    SPATH=`readlink $SPATH`
fi

n=4
while [ 0 -lt "$n" ]; do SPATH=`dirname $SPATH`; let n=n-1; done
PATHS=""
for p in $SPATH/gtknode-*/ebin $SPATH/eper-*/ebin; do
    if [ "${p: -7}" == "-*/ebin" ]; then
        echo "Can't expand $p.${p: -7}"
    else
        PATHS=$PATHS" -pa $p"
    fi
done

detach="-detached"
VSN=""
START="-s gperf ni"
HALT="-s erlang halt"
XTRA=""

while [ -n "$1" ]
  do
  case $1 in
      "-help"|"-h"|"-?")
          usage
          ;;
      "-win")
          WIN="xterm -sb -sl 9999 -bg gold -fg black -e"
          START="-s gperf start"
          HALT=""
          detach=""
          ;;
      "-dbg")
          START="-s gperf start"
          HALT=""
          detach=""
          ;;
      "-vsn"|"-version")
          shift
          VSN="+R $1"
          ;;
      "-nettick"|"-tick")
          shift
          nettick="-kernel net_ticktime $1"
          ;;
      "-cookie"|"-setcookie")
          shift
          cookie="-setcookie $1"
          ;;
      "-nocookie")
          cookie=""
          ;;
      "-pa")
           shift
           XTRA="-pa $1 $XTRA"
           ;;
      "-proxy")
          shift
          proxy="$1"
          ;;
      "-*")
          echo dollar_one $1
          ;;
      *)
          XTRA="$XTRA $1"
          ;;
  esac
  shift
done

name="gperf_"$$
FLAGS="$detach -boot start_sasl -sasl errlog_type error +A16"
DISTR="-hidden -sname $name $cookie $nettick"

$WIN erl $VSN $FLAGS $DISTR $PATHS $START $XTRA $proxy $HALT
