#!/bin/bash

OCAML_MIN_VER="4.02"

verge() {
    # osx doesn't have sort -V
    # [  "$2" = "`echo -e "$1\n$2" | sort -V | head -n1`" ]
    [ "$2" = "`echo -e "$1\n$2" | tr ' ' '\n' | sort -n | head -n1`" ]
}

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

OCAML_VER="`ocamlc -version`"

if verge "$OCAML_VER" "$OCAML_MIN_VER"; then
    echo "ocamlc version $OCAML_VER >= $OCAML_MIN_VER ... OK"
else
    echo "OCaml version $OCAML_MIN_VER or newer needed"
    echo "Configuration script failed!"
    exit 1
fi

if camlp5 -v >/dev/null 2>&1; then
    echo "camlp5 ... OK"
else
    echo "You need the command camlp5 accessible in the path!"
    echo "Configuration script failed!"
    exit 1
fi

if [ "`echo 'print_endline Sys.os_type;;' | ocaml -stdin -noprompt`" = "Unix" ]; then
    echo "OS type ... Unix"
    cp tools/Makefile.inc.unix tools/Makefile.inc
else
    echo "OS type ... Windows"
    cp tools/Makefile.inc.win tools/Makefile.inc
fi

D_GW_DIR=`pwd`/
if test -e "tools/Makefile.inc"; then
  sed "s|^\(GW_DIR=\).*|\1$D_GW_DIR|" tools/Makefile.inc > tools/Makefile.inc.tmp
  mv tools/Makefile.inc.tmp tools/Makefile.inc
fi

cp tools/Makefile.ocaml.inc tools/Makefile.ocaml

if ocamlfind printconf >/dev/null 2>&1; then :
else
    echo "Could not find ocamlfind in the path."
    echo "You may need to update Makefile.ocaml by hand."
    exit 1
fi

D_CAMLP5D=`ocamlfind query camlp5`/
if test -e "tools/Makefile.ocaml"; then
  sed "s|^\(CAMLP5D=\).*|\1$D_CAMLP5D|" tools/Makefile.ocaml > tools/Makefile.ocaml.tmp
  mv tools/Makefile.ocaml.tmp tools/Makefile.ocaml
fi

echo "Configuration script succeeded!"
