#!/bin/sh
die() {
    echo -e "$@"
    exit 1
}

MAKE=${MAKE-make}
CMAKE=${CMAKE-cmake}
PACKAGE=divine-mc

test -e configure.vars && source ./configure.vars

test -d _darcs && DARCS=true

$DARCS || test -f manifest || die \
    "Sorry, the file \"manifest\" appears to be missing from the distribution;\n\
please make sure you are running this script in the source directory."

cat manifest 2> /dev/null | while read REPLY; do
    test -e "$REPLY" || die \
        "Sorry, but file \"$REPLY\" appears to be missing from the distribution;\nplease make sure your tarball is complete.";
done

do_cmake_inst() {
    CMAKE_VER=2.8.9;
    CMAKE_DIR="cmake-$CMAKE_VER";
    CMAKE_TAR="$CMAKE_DIR.tar.gz";
    CMAKE_URL="http://www.cmake.org/files/v2.8/$CMAKE_TAR";
    if ! test -e "$CMAKE_TAR"; then
        if type -p curl >& /dev/null; then
            curl $CMAKE_URL -o cmake-$CMAKE_VER.tar.gz || die "Error downloading cmake, plase install manually.";
        elif type -p wget >& /dev/null; then
            wget $CMAKE_URL || die "Error downloading cmake, please install manually.";
        else
            die "Could not find curl nor wget to download cmake: plase install either of them or install cmake manually."
        fi
    fi
    test -e "$CMAKE_TAR" || die "Cmake tarball unexpectedly missing."
    tar xvzf "$CMAKE_TAR" || die "Error unpacking cmake tarball."
    (cd "$CMAKE_DIR" ; ./bootstrap) || die "Error bootstrapping cmake."
    (cd "$CMAKE_DIR" ; $MAKE) || die "Error building cmake."
    echo "CMAKE=\""'`pwd`'"/$CMAKE_DIR/bin/cmake\"" > configure.vars;
    source ./configure.vars
    echo "Done downloading and compiling cmake, proceeding with configuration."
}

cmake_inst() {
    echo -ne \
"Sorry, but CMake is required to build $PACKAGE, please install it from\n\
your distribution packages or from http://www.cmake.org. If you do not have\n\
root permissions and therefore do not want to install cmake system-wide,\n\
i can try to download and compile cmake for you.\n\n\
Download and install cmake? [y/n]"
    read answer;
    if test "$answer" = "y" || test "$answer" = "Y"; then
        do_cmake_inst;
    else
        die "Not proceeding, please re-run configure after installing cmake".
    fi
}

$CMAKE --version 2>&1 > /dev/null || cmake_inst
$CMAKE --version 2>&1 > /dev/null || die "$CMAKE unexpectedly failed."

test -e _build && die "The directory \"_build\" already exists, please remove it before reconfiguring."

mkdir _build || die "Failed to create _build, permission problem?"
(cd _build; $CMAKE .. "$@") || die "Configuration failed."

echo

echo -e "Configuration complete. You may use \"ccmake _build\" or \n\
supply options of form -DOPTION=value to this script, if you need to \n\
adjust any of the configuration options."
echo
