#!/bin/sh

# Do not change these variables directly. Use options to modify the behavior of
# the script (see usage).
VERBOSE="false"
WITHOCAML="false"
OCAMLFOLDER="ocaml"
PACKAGES="pcre-ocaml ocamlnet pxp ocurl ocaml-expat ocamlsdl ounit"

usage ()
{
    echo "Usage: $0 [OPTION]... [MLVERSION]"
    echo "Configures opam for the compilation of CDuce."
    echo "Switches the OCaml version of opam if MLVERSION is provided."
    echo "Example: $0 --verbose --mliface=ocaml 4.01.0"
    echo "Valid options are:"
    echo "\t-v, --verbose\tactivate verbose mode"
    echo "\t--mliface=DIR\tcheckout the OCaml sources in DIR to MLVERSION"
    echo "\t-h, --help\tdisplay this help and exit"
}

# Parse options

while test $# -ge 1; do
    if test $1 = "-v" || test $1 = "--verbose"; then VERBOSE="true";
    elif echo $1 | grep -qse "--mliface=.*"; then
	WITHOCAML="true"; OCAMLFOLDER=`echo $1 | cut -d '=' -f 2`;
    elif test $1 = "-h" || test $1 = "--help"; then usage; exit 0;
    elif echo $1 | grep -qse "-.*"; then usage; exit 1;
    else break; fi;
    shift;
done

# Switching opam's version of OCaml

if test $# -ge 1; then

    echo -n "Switching to version $1 of OCaml..."
    opam switch $1 > /dev/null 2>&1

    if test $? -ne 0; then
	echo "failed. This version doesn't seem to exist."; exit 2;
    fi

    echo "done."

    echo "# To complete the configuration of OPAM, you need to run:"
    echo "eval \`opam config env\`"
fi

# Installing packages

echo "Installing mandatory packages to compile CDuce."
for i in $PACKAGES; do opam install $i; done

# Checkout git repository of OCaml sources to appropriate version.

if test $WITHOCAML = "true" && test $# -ge 1; then
    if test -d $OCAMLFOLDER; then
	cd $OCAMLFOLDER; git checkout $1 > /dev/null 2>&1
	echo "OCaml sources updated to version $1."
    else
	echo "Couldn't find $OCAMLFOLDER. The interface will not be built."
    fi
fi
