#!/bin/sh
#
# A simple shell script to start interactive read-eval-print loop of
# a Curry system together with CPM to compute the actual load path
# and rlwrap to support input line editing.

###########################################################################
# Adapt the following definitions to the actual Curry system:

SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT")

CURRYHOME=$(dirname "$SCRIPTPATH")
export CURRYHOME

# The executable of the Curry REPL installed by CPM:
REPL="$CURRYHOME/bin/kmcc_repl"

if [ -x "$CURRYHOME/bin/cypm" ] ; then
  WHICHCPM="$CURRYHOME/bin/cypm"
else
  WHICHCPM=`which cypm`
fi

###########################################################################
# If the first argument is 'cypm', invoke the Curry Package Manger
# where this script is set as the Curry binary:
if [ "$1" = cypm ] ; then
  if [ ! -x "$WHICHCPM" ] ; then
    echo "Cannot invoke CPM: executable 'cypm' not found!"
    exit 1
  fi
  shift
  exec "$WHICHCPM" -d curry_bin="$SCRIPT" ${1+"$@"}
fi

###########################################################################
# Invoke the Curry REPL with CPM to compute CURRYPATH:

# Check whether we should call CPM to compute the correct load path:
if [ ! -d "$HOME" ] ; then
  USECPM=no   # do not use CPM without a home directory
elif [ -x "$WHICHCPM" ] ; then
  CYPMBIN=$WHICHCPM
  USECPM=yes
else
  USECPM=no
fi

# Use readline wrapper `rlwrap` for REPL if `rlwrap` exists,
# we have tty as stdin, and we have a home dir to store rlwrap's history:
USERLWRAP=no
if tty -s ; then
  RLWRAP=`which rlwrap`
  if [ -d "$HOME" ] ; then
    USERLWRAP=yes
  fi
fi

# check arguments for appropriate settings:
for i in $* ; do
  case $i in
    --help | -h | -\? ) USECPM=no ;;
    --version | -V    ) USECPM=no ;;
    --numeric-version | --compiler-name | --base-version ) USECPM=no ;;
    --nocypm | -n ) USECPM=no ;;
    --noreadline ) USERLWRAP=no
  esac
done

if [ ! -x "$REPL" ] ; then
  echo "ERROR: executable '$REPL' not found!" >&2
  echo "Run: cd $CURRYHOME && make" >&2
  exit 1
fi

if [ $USECPM = yes ] ; then
  # set CURRYPATH with 'deps' command of CPM
  echo "Compute CURRYPATH with '$CYPMBIN'..."
  CPMPATH=`"$CYPMBIN" -v quiet -d CURRYBIN="$REPL" deps -p`
  if [ $? -gt 0 ] ; then
    echo $CPMPATH
    exit 1
  fi
  if [ -n "$CURRYPATH" ] ; then
    CURRYPATH=$CURRYPATH:$CPMPATH # keep existing CURRYPATH setting
  else
    CURRYPATH=$CPMPATH
  fi
  export CURRYPATH
fi

# do not use rlwrap inside emacs:
if [ "$TERM" = dumb ] ; then
  USERLWRAP=no
fi

if [ $USERLWRAP = yes ] ; then
  exec rlwrap -c "$REPL" ${1+"$@"}
else
  exec "$REPL" ${1+"$@"}
fi
