#!/bin/sh
#  Launch a ruby ESP control script in the appropriate environment
[ -n "$ESPhome" ] || export ESPhome="`dirname $0`/.."
script="$1"
kickstart="ruby $ESPhome/lib/esp.rb"
case $script in
  -help | --help)  echo "Usage:  `basename $0` {script} {args}"
       echo "Launches ruby ESP script with optional args"
       echo "Searches for the script on this ESPpath:"
       echo "  $ESPpath"
       echo "If no script specified, an interactive ESP ruby session is started"
       exit 100
  ;;
  "" | -*) exec $kickstart "$@"
  ;;
esac
shift

# find $1 on $ESPpath
# output the full path
ESPwhich ()
{
  fn="$1"
  IFS=:
  set $ESPpath
  for field; do
    fullPath="$field/$fn"
    if [ -r "$fullPath" ]; then
      echo -n $fullPath
      return 0
    fi
  done
  return 1
}

scriptPath="$script"
#if there's an ESPpath and the script name specifies no directory, go looking...
if [ "$ESPpath" -a "$script" = "`basename $script`" ]; then
  scriptPath=`ESPwhich $script`
  if [ $? != 0 ]; then
      #append .rb if script name didn't already end in .rb
    [ "$script" = "${script%.rb}" ] && scriptPath=`ESPwhich $script.rb`
    if [ $? != 0 ]; then
      echo "No '$script' script found on:"
      echo "  $ESPpath"
      exit 1
    fi
  fi
else
  if [ "$script" = "${script#/}" ]; then  #relative path name with directory
    [ ! -r "$scriptPath" -a ! -r "${scriptPath%.rb}.rb" ] && \
      scriptPath="$ESPhome/$script"  #try basing at ESPhome
  fi
fi
[ ! -r "$scriptPath" -a "$scriptPath" = "${scriptPath%.rb}" ] && \
  scriptPath="$scriptPath.rb"
exec $kickstart "$scriptPath" "$@"
