#!/bin/bash

REDWOODS=${LOGONROOT}/lingo/redwoods;

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

. ${LOGONROOT}/etc/library.bash;

source="--source";

while [ $# -gt 0 -a "${1#-}" != "$1" ]; do
  case ${1} in
    --32)
      LOGONOS=${LOGONOS%%.??}.32;
      shift 1;
    ;;
    --source)
      source="--source";
      shift 1;
    ;;
    --binary)
      unset source;
      shift 1;
    ;;
    --cat)
      cat="--cat";
      shift 1;
    ;;
    --increment)
      increment=${2};
      shift 2;
    ;;
    --percentile)
      percentile=${2};
      shift 2;
    ;;
    --gc)
      gc=yes;
      shift 1;
    ;;
  esac
done

if [ -z "${1}" ]; then 
  echo "usage: load <load file>.";
  exit 1;
fi


load=$1;

log=${load%%.lisp}.${HOSTNAME}.$(date "+%Y-%m-%d-%H:%M:%S");

unset DISPLAY;

cd ${REDWOODS};

{
  if [ -n "${source}" ]; then
    echo "(pushnew :lkb *features*)";
    echo "(pushnew :logon *features*)";
    echo "(load \"${LOGONROOT}/lingo/lkb/src/general/loadup.lisp\")";
    echo "(compile-system \"tsdb\")";
  fi

  if [ -n "${gc}" ]; then
    echo "(setf tsdb::*tsdb-gc-verbosity* '(:stats))";
    echo "(setf tsdb::*tsdb-gc-debug*
            (cons
             '((1 :new) (5 :old :room))
             '((1 :new :old :holes :room))))";
  fi

  echo "(lkb:read-script-file-aux \"${REDWOODS}/erg/lkb/script\")";
  echo "(load \"${REDWOODS}/dot.tsdbrc\")";
  if [ -n "${increment}" ]; then
    echo "(setf tsdb::%redwoods-items-increment% ${increment})";
    echo "(setf tsdb::%redwoods-items-percentile% nil)";
  elif [ -n "${percentile}" ]; then
    echo "(setf tsdb::%redwoods-items-percentile% ${percentile})";
  fi
  echo "(load \"${load}\")"; \
  echo "(excl:exit 0 :no-unwind t)";

} | $LOGONROOT/bin/logon ${source} ${cat} \
    -I base -locale en_US.UTF-8 -qq 1>&1 | tee ${log}