#!/bin/sh

dotNED=.ned

# ------------------------------------------------------------------------------

debug ()
  {
  [ -n "$NED_DEBUG" ] && echo "$@"  1>&2
  }

debuglines ()
  {
  local s
  for s in "$@"; do
    debug "$s"
  done
  }

usage ()
  {
  debug=yes
  debuglines \
    "$this [-h] [-debug] [directory] {parameters to $dotNED or nc -noask}"     \
    ""                                                                         \
    "Invokes a NEdit server as follows --"                                     \
    "If the first argument is a directory, go there. Then execute the $dotNED" \
    "script file in the current directory or one of the current path's"        \
    "bases. If none is found, try to find one in \$HOME, otherwise call"       \
    "nc -noask. All parameters after the directory, if present, are passed"    \
    "to the script other than -h (which prints this information) or -debug"    \
    "(which traces the actions of this command)."
  }

# ------------------------------------------------------------------------------

this=`basename $0`

# handle -debug, -h options
while true; do
  case "x$1" in
    x-debug)
      NED_DEBUG=yes
      export NED_DEBUG
      shift
      ;;
    x-h*)
      usage
      exit
      ;;
    *)
      break
      ;;
  esac
done

# do we have an initial directory argument? if so, go there
if [ -d "$1" ]; then
  # a directory was passed to this script - go there
  debug "${this}: \$1 is a directory: doing cd $1; shift"
  cd "$1"
  shift
fi

# find suitable $dotNED script
cur=`pwd`
[ -z "$cur" ] && cur=.

if [ -f $dotNED ] && [ -x $dotNED ]; then
  debug "${this}: cmd = '$dotNED' (in $cur)"
  cmd="$dotNED"
else
  # move up the hierarchy until we find a $dotNED script we can execute
  neddir="$cur"
  while [ "$neddir" != "." ] && \
        [ ! -x "$neddir/$dotNED" ]; do
    debug "${this}: looking for $dotNED in $neddir"
    [ "$neddir" = "/" ] && break
    neddir=`dirname $neddir`
  done

  if [ -x "$neddir/$dotNED" ]; then
    debug "${this}: cmd = '$neddir/$dotNED'"
    cmd="$neddir/$dotNED"
  elif [ -f "$HOME/$dotNED" ] && [ -x "$HOME/$dotNED" ]; then
    debug "${this}: cmd = '$HOME/$dotNED' (home)"
    cmd="$HOME/$dotNED"
  else
    # no $dotNED script - just use plain nc
    debug "${this}: cmd = 'nc -noask' (in $cur)"
    cmd="nc -noask"
  fi
fi

# invoke the command chosen (if $1 is our $dotNED file, drop it!)
if [ x"$1" = x"$cur/$dotNED" ] || [ x"$1" = "x$dotNED" ]; then
  debug "${this}: \$1 is $1: dropping it"
  shift
elif [ x"$1" = x"$cur" ]; then
  debug "${this}: \$1 is pwd ($1): dropping it"
  shift
fi
debug "${this}: executing exec setsid $cmd $*"
eval setsid $cmd "$@"
