#!/usr/bin/env bash
###########################################
## CHomP
###########################################

if [ "$SAGE_LOCAL" = "" ]; then
   echo "SAGE_LOCAL undefined ... exiting";
   echo "Maybe run 'sage -sh'?"
   exit 1
fi

if [ "x$CXXFLAG64" = x ] ; then
    CXXFLAG64=-m64
fi

if [ "x$SAGE64" = xyes ] ; then
    CXXFLAGS="$CXXFLAGS $CXXFLAG64"
    export CXXFLAGS
fi

case `uname` in
    "Darwin")
	target='mac';;
    "SunOS")
	compiler_flags="-O2 -pedantic -Wall"
	LDFLAGS="$LDFLAGS -s"
	export LDFLAGS
        target='sun';;
    *)
	compiler_flags="-O2 -ansi -pedantic -Wall"
	LDFLAGS="$LDFLAGS -s"
	export LDFLAGS
	target='unx';;
esac

export compiler_flags

# patch src/include/capd/capd/operatingSystemSetting.h so that it
# detects Solaris on x86 as well as on sparc.
cp patches/operatingSystemSetting.h src/include/capd/capd/

cd src

# Do not exit script if there is an error, but instead print an
# informative error message. This is helps in determining why the
# configuration, compilation or installation failed. So put this before
# the make command.
set +e

$MAKE -j1 target=$target COMPILE="${CXX} ${CXXFLAGS} ${compiler_flags}" LINK="${CXX} ${CXXFLAGS} ${LDFLAGS}"
if [ $? -ne 0 ]; then
    echo "Error building CHomP"
    exit 1
fi

install bin/homchain bin/homsimpl bin/homcubes $SAGE_LOCAL/bin/
if [ $? -ne 0 ]; then
    echo "Error installing CHomP"
    exit 1
fi
