#!/bin/bash

# This .ned script starts a NEdit server

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

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

fail ()
  {
  echo "$@"  1>&2
  exit 1
  }

findHereOrAbove ()
  {
  # $1 is the start directory, $2... is the test content, in which the sequence
  # /./ is interpreted as the directory under test.
  # Echos the directory satisfying the test, if any.
  [ $# -lt 2 ] && fail "${fn}: missing parameters"

  local tst for_d d="$1"
  shift
  fn=findHereOrAbove

  # initial checks
  [ "$d" = . -o "$d" = "" ] && d=${PWD:-`pwd`}
  [ "$d" = . -o "$d" = "" ] && fail "${fn}: cannot determine directory: '$d'"
  [ ! -d "$d" ] && fail "${fn}: '$d' not a directory"
  [ ! -r "$d" ] && fail "${fn}: '$d' not a readable directory"

  # search
  while true; do
    tst=`echo "$*" | sed -e "s:/\./:$d/:g"`

    [ "x$tst" = "x$*" ] && for_d=" (for $d)"

    [ ! -r "$d" ] && return 1               # failed: cannot read $d
    debug "${fn}: test='$tst'$for_d"
    eval "( $tst ) 1>/dev/null 2>&1 </dev/null"
    res=$?
    [ $res -gt 1 ] && fail "${fn}: bad test '$tst'$for_d"
    if [ $res = 0 ]; then
      debug "${fn}: test='$tst' success"
      echo "$d"
      return 0
    fi
    [ "$d" = "/" ] && return 1              # failed: test not satisfied
    d=`dirname "$d"`                        # -- iterate
  done
  }

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

# do we already have a server running? if so, use it
# NB this depends on nc failing when given empty input
if [ -n "$NED_SERVERNAME" ]; then
  if : | nc -ask -svrname "$NED_SERVERNAME" "$@" > /dev/null 2>&1; then
    exit    # great: all done
  fi
fi

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

NED_SCRIPTFILE="$0"
export NED_SCRIPTFILE

d=`pwd 2>/dev/null || echo \$PWD`

dotNedDir=`dirname "$0"`                # where this script was found
dotNedDir=`cd $dotNedDir; echo \$PWD`

runDir="$d"                             # where we will be running
NED_RUNDIR="$runDir"
export NED_RUNDIRECTORY

NEDIT_COLORS=${NEDIT_COLORS:-${NEDIT_COLOR}}    # misspelt NEDIT_COLORS?
export NEDIT_COLORS

debug "NEDIT_COLORS=$NEDIT_COLORS"
debug "dotNedDir=$dotNedDir"
debug "runDir=$runDir"

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

# see if we can find tags files
if [ -z "$NED_TAGS" ]; then
  debug "Looking for tags files"
  tagsIn=`findHereOrAbove "$d" [ -f /./tags ]`
  if [ -n "$tagsIn" ]; then
    debug "Found tags file: $tagsIn/tags"
    tags="nedit.tagFile: $tagsIn/tags"
    NED_TAGS="$tags"
  fi
fi
if [ -n "$NED_TAGS" ]; then
  tags="$NED_TAGS"
  export NED_TAGS
fi

# do we need a NEDIT_HOME set up?
needNEDIT_HOME=""
[ -z "$NEDIT_HOME" ] && needNEDIT_HOME=yes
[ -n "$NEDIT_HOME" ] && [ ! -d "$NEDIT_HOME" ] && needNEDIT_HOME=yes

if [ -n "$needNEDIT_HOME" ]; then
  # see if we can find a .nedit[-dark] directory
  # try .nedit-dark first, if colors require it, but take a .nedit if closer
  if [ `expr "$NEDIT_COLORS" : dark` -gt 0 ]; then
    debug 'Looking for a NEdit home directory: .nedit-dark or .nedit'
    nhomedir=`findHereOrAbove "$d" [ -d /./.nedit-dark -o -d /./.nedit ]`
    nhome="$nhomedir/.nedit"
    [ -d "${nhome}-dark" ] && nhome="${nhome}-dark"
  fi

  # colors may not be dark so, if we haven't found anything, look for .nedit
  if [ -z "$nhomedir" ]; then
    debug 'Looking for a NEdit home directory: .nedit'
    nhomedir=`findHereOrAbove "$d" [ -d /./.nedit ]`
    nhome="$nhomedir/.nedit"
  fi

  # if we still haven't found anything, look for .nedit in $HOME
  if [ -z "$nhomedir" ]; then
    debug 'Looking for a NEdit home directory in $HOME: .nedit'
    nhome="$HOME/.nedit"
    [ -d "$nhome" ] && nhomedir="$HOME"
  fi

  # check results: override $NEDIT_HOME only if it doesn't already exist
  if [ -n "$nhomedir" ]; then
    debug "Setting NEDIT_HOME=$nhome"
    NEDIT_HOME="$nhome"
    export NEDIT_HOME
    NED_NEDIT_HOME="NEDIT_HOME=$nhome"
    export NED_NEDIT_HOME
  fi
fi

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

# server name - uses the directory path, munging it into a valid name
sn="$runDir"                            # what of "$dotNedDir", "$NEDIT_HOME"?

if [ -n "$sn" ]; then
    NED_SERVERDIR="$sn"
    export NED_SERVERDIR

    dotNed="$dotNedDir/`basename $0`"
    NED_SCRIPTFILEFULL="$dotNed"
    export NED_SCRIPTFILEFULL

    colorName="${NEDIT_COLORS:+___color_}${NEDIT_COLORS}"

    so=-svrname
    sn="NED_${sn}___dotNED_${dotNed}${colorName}"
    sn=`echo "$sn" | sed -e "s:/:_D_:g" \
                         -e "s:\\.:_d_:g" \
                         -e "s/:/_c_/g" \
                         -e "s/-/_m_/g" \
                         -e "s/[^A-Za-z0-9]/_/g"`
fi
NED_SERVERNAME="$sn"
export NED_SERVERNAME

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

# Colors: we assume that the nedit.rc settings in $NEDIT_HOME (which should be
# called .../.nedit or .../.nedit-dark) are compatible with the choice of color
# scheme. Here, depending on the scheme, we override various color values.

fixedColor="y"

case "$NEDIT_COLORS" in
  yellow)
    # --- set pale yellow backgrounds ---------
    fgCol=black
    bgCTypes='32-255:#ffffe0;0-31,127:red;128-159:orange;9,10,13:#e7e7c0;160:#fffff0'
    bgCol='#f7f7d0'
    fgWrp='#d0d0a0'
    bgXmT="$bgCol"
    ;;
  green)
    # --- set pale green backgrounds --------
    # text bg: #e6fff0
    # tabs bg: #c0e0d8 ( < bg) #c8e8e0 ( < bg) #d8fcf0 ( > bg)
    # full bg: #d0f4e8
    fgCol=black
    bgCTypes='0-8,11-31,127:red;9,10:#c8e8e0;32-126,160-255:#e6fff0;128-159:orange'
    bgCol='#d0f4e8'
    fgWrp='#a0d0c0'
    bgXmT="$bgCol"
    ;;
  blue)
    # --- set pale blue backgrounds --------
    fgCol=black
    bgCTypes='0-8,10-31,127:red;9:#c0e0f0;32-126,160-255:#e0f8ff;128-159:orange'
    bgCol='#d0f0ff'
    fgWrp='#a0c0d0'
    bgXmT="$bgCol"
    ;;
  grey)
    # --- set greyish backgrounds (like NEdit's default colour scheme) ---------
    fgCol=black
    bgCTypes='0-8,10-31,127:red;9:#dedede;32-126,160-255:#f0f0f0;128-159:orange'
    bgCol='#e5e5e5'
    fgWrp='#b0b0b0'
    bgXmT="$bgCol"
    ;;
  white)
    # --- set white/grey backgrounds ---------
    fgCol=black
    bgCTypes='0-8,10-31,127:red;9:#ececec;32-126,160-255:white;128-159:orange'
    bgCol='#f4f4f4'
    fgWrp='#c0c0c0'
    bgXmT='white'
    ;;
  darkblue)
    # --- set dark blue backgrounds --------
    fgCol=white
    bgCTypes='32-255:#002050;0-31,127:red;128-159:brown;9,10,13:#000040;160:#004080'
    bgCol='#001040'
    bgSel='#0070d0'	# lighter blue - or #007070
    fgWrp='#003060'
    bgXmT="$bgCol"
    ;;
  darkgreen)
    # --- set dark green backgrounds --------
    fgCol=white
    bgCTypes='32-255:#005050;0-31,127:red;128-159:brown;9,10,13:#003838;160:#008080'
    bgCol='#004040'
    fgWrp='#004830'
    #bgSel='#603020'	# brown - or #803020
    #bgSel='#008060'	# dim bluish green
    bgSel='#0070d0'	# lighter blue - or #007070
    bgXmT="$bgCol"
    ;;
  *)
    fixedColor=""	# turn off fixed colors
    ;;
esac

# Build the command line
cmd="nc -noask $so $sn"
[ -n "$tags" ] && cmd="$cmd -xrm '$tags'"
if [ "$fixedColor" = "y" ]; then
  cmd="$cmd -xrm 'nedit*XmText.foreground: $fgCol'"
  cmd="$cmd -xrm 'nedit*XmList.foreground: $fgCol'"
  cmd="$cmd -xrm 'nedit*XmTextField.foreground: $fgCol'"
  cmd="$cmd -xrm 'nedit*XmText.background: $bgXmT'"
  cmd="$cmd -xrm 'nedit*XmList.background: $bgXmT'"
  cmd="$cmd -xrm 'nedit*XmTextField.background: $bgXmT'"
  cmd="$cmd -xrm 'nedit.textBgColor: $bgCol'"
  cmd="$cmd -xrm 'nedit.wrapMarginForeground: $fgWrp'"
  cmd="$cmd -xrm 'nedit.backlightCharTypes: $bgCTypes'"
  [ -n "$bgSel" ] && cmd="$cmd -xrm 'nedit.selectBgColor: $bgSel'"
fi

NED_COMMANDBASE="$cmd"
export NED_COMMANDBASE

NED_COMMAND="$cmd $*"
export NED_COMMAND

eval "$cmd" "$@"
