#!/bin/bash

if [ -z "${LOGONROOT}" ]; then
  #
  # determine the LOGON root directory, assuming this script resides in a 
  # `bin' sub-directory that is shared across platforms.
  #
  path=$(dirname $0)
  if [ "${path#./}" != "${path}" ]; then
    path="$(pwd)/${path#./}"
  fi
  if [ "${path#/}" = "${path}" ]; then
    if [ "${path}" = "." ]; then
      path="$(pwd)";
    else 
      path="$(pwd)/${path}"
    fi
  fi
  LOGONROOT="${path%/bin}";
  export LOGONROOT
fi

if [ ! -f ${LOGONROOT}/etc/library.bash ]; then
  echo "logon: unable to determine \$LOGONROOT source directory; exit"
  exit 1;
fi

. ${LOGONROOT}/etc/library.bash

#
# at this point, parse the options that modify our own behaviour
#
while [ "${1}" == "--32" \
        -o "${1}" == "--source" -o "${1}" == "--naked" \
        -o "${1}" == "--binary" -o "${1}" == "--runtime" \
        -o "${1}" == "--tty" \
        -o "${1}" == "-I" -o "${1}" == "-e" ]; do
  case "${1}" in
    --32)
      LOGONOS=${LOGONOS%%.??}.32;
      shift 1;
    ;;
    --source|--naked)
      source=yes;
      shift 1;
    ;;
    --binary|--runtime)
      unset source;
      shift 1;
    ;;
    --tty)
      unset DISPLAY
      shift 1;
    ;;
    -I)
      image=${2};
      shift 2;
    ;;
    -e)
      execute=${2};
      shift 2;
  esac
done

#
# and now see whether we actually have a source-enabled tree, including a copy 
# of Allegro CL and a suitable license file.  if not, revert to binary-only.
#
if [ ! -f ${LOGONROOT}/franz/${LOGONOS}/devel.lic ]; then
  unset source;
fi

#
# for debugging purposes, simply pass through out incoming commands
#
if [ "${1}" == "--cat" ]; then
  exec /bin/cat;
fi

if [ -z "${source}" ]; then
  exec ${LOGONROOT}/lingo/lkb/${LOGONOS}/logon \
    -L ${LOGONROOT}/dot.clinit.cl "$@";
else
  if [ -z "${image}" ]; then
    if [ -z "${execute}" ]; then
      exec ${LOGONROOT}/franz/${LOGONOS}/alisp "$@" \
        -L ${LOGONROOT}/dot.clinit.cl "$@";
    else
      exec ${LOGONROOT}/franz/${LOGONOS}/alisp -e "${execute}" "$@" \
        -L ${LOGONROOT}/dot.clinit.cl "$@";
    fi
  else
    if [ -z "${execute}" ]; then
      exec ${LOGONROOT}/franz/${LOGONOS}/alisp -I ${image} \
        -L ${LOGONROOT}/dot.clinit.cl "$@";
    else
      exec ${LOGONROOT}/franz/${LOGONOS}/alisp -I ${image} \ 
        -L ${LOGONROOT}/dot.clinit.cl -e "${execute}" "$@";
    fi
  fi
fi