#!/bin/sh

BINDIR=/usr/local/bin
LIBDIR=/usr/local/lib/camlp4
MANDIR=/usr/local/man/man1

if test -f config/Makefile.cnf; then . config/Makefile.cnf; fi

abort ()
{
	echo
	echo Configuration not changed
	exit 1
}

trap abort 2

askfor ()
{
	echo "$1 [$2]"
	echo -n "? "
	r=""
	read r
	if test $? -ne 0; then abort; fi
	r=`eval echo $r`
	case `expr "$r" : "\(.\)" "|" "\1"` in
		"/" | "\1" ) ;;
		*) r=`pwd`/$r;;
	esac
	if test "$r" = ""; then r=$2; fi
}

echo "This shell script creates or updates the file config/Makefile.cnf."
echo "At any time you can interrupt it by control-C or control-D."
echo "In these cases, the file config/Makefile.cnf is not modified."
echo

if ocamlc -v 2>&1; then
	:
else
        echo "You need the command ocamlc accessible in the path!"
        echo "Configuration script failed!"
        exit 1
fi

CAMLVERSION=`ocamlc -v | sed -n -e 's|.*version* *\(.*\)$|\1|p' `

case $CAMLVERSION in
  1*|2.00*|2.01*|2.02*|2.03*)
        echo "Your version of Objective-Caml is $CAMLVERSION."
        echo "You need Objective-Caml 2.04!"
        echo "Configuration script failed!"
        exit 1;;
  2.*)   echo "You have Objective-Caml $CAMLVERSION. Good!";;
  ?*)   echo "You have Objective-Caml $CAMLVERSION. Good!";;
  *) echo "I found the Objective-Caml compiler but cannot find version number!"
     echo "Is it installed properly ?"
     echo "Configuration script failed!"
     exit 1;;
esac

OLIBDIR=`ocamlc -v | sed -n -e 's/Standard library directory: //p'`
OLIBDIR=`echo $OLIBDIR | sed -e s=\\\\\\\\=/=g`
echo "Ocaml library directory is $OLIBDIR"

echo
echo "The compilation process creates executable files."
echo "Please tell me where to install them."
askfor "Directory for executables" $BINDIR
BINDIR=$r

echo
echo "The compilation process creates some library files."
echo "Please tell me where to install them."
askfor "Directory for library" $LIBDIR
LIBDIR=$r

echo
echo "The system has some manual pages."
echo "Please tell me where to install them."
askfor "Directory for manual pages" $MANDIR
MANDIR=$r

(
echo OLIBDIR=$OLIBDIR
echo BINDIR=$BINDIR
echo LIBDIR=$LIBDIR
echo MANDIR=$MANDIR
) > config/Makefile.cnf

rm -f config/Makefile
cat config/Makefile.tpl > config/Makefile
echo >> config/Makefile
cat config/Makefile.cnf >> config/Makefile

echo
echo "Resulting configuration file (config/Makefile.cnf):"
cat config/Makefile.cnf
