#!/bin/sh

ROOT=$(git rev-parse --show-toplevel)
[ -z $BUILD ] && BUILD=Debug
[ -z "$CC" ] && [ ! -z `which clang` ] && CC="clang"
[ -z "$CC" ] && [ ! -z `which gcc` ] && CC="gcc"
[ -z "$CC" ] && [ ! -z `which tcc` ] && CC="tcc"
[ -z "$CC" ] && [ ! -z `which cc` ] && CC="cc"

MACHINE=`$CC -dumpmachine`
[ -z $MACHINE ] && MACHINE=`uname -m`
BIN_DIR="$ROOT/build-$MACHINE-$CC-$BUILD"
mkdir -p $BIN_DIR
rm -f $BUILD
ln -sf $BIN_DIR $BUILD

rm -f CMakeCache.txt

# use anything installed in /opt or /usr
LIBRARY_PATH=/opt/lib:/opt/lib/$MACHINE:/usr/lib/$MACHINE
INCLUDE_PATH=/opt/include:/usr/include
PREFIX_PATH=/opt

# I like to put stuff in ~/usr if I don't have permission to install packages on the machine:
if [ -d $HOME/usr ]; then
  LIBRARY_PATH=$HOME/usr/lib:$HOME/usr/lib/$MACHINE:$LIBRARY_PATH
  INCLUDE_PATH=$HOME/usr/include:$HOME/usr/include/$MACHINE:$INCLUDE_PATH
  PREFIX_PATH=$HOME/usr:$HOME/usr/local:$PREFIX_PATH
fi

DEST=$(dirname $ROOT)/server
ARGS=" -DCMAKE_MODULE_PATH=$ROOT/cmake/Modules \
 -DCMAKE_BUILD_TYPE=$BUILD \
 -DCMAKE_LIBRARY_PATH=$LIBRARY_PATH \
 -DCMAKE_INCLUDE_PATH=$INCLUDE_PATH \
 -DCMAKE_PREFIX_PATH=$PREFIX_PATH \
 -DCMAKE_INSTALL_PREFIX=$DEST"

git submodule update --init

path="$(which tolua)"
if [ "$HAVE_TOLUA" = "0" ] || [ -z $path ] ; then
 echo "tolua is not installed, building from source"
 cd $ROOT
 if [ ! -d tolua ]; then
  LUA_VERSION="5.2"
  if [ -d /usr/include/lua5.1 ] || [ -d /usr/local/include/lua5.1 ]; then
   LUA_VERSION="5.1"
  fi
  echo "fetching tolua ${LUA_VERSION} from github..."
  git clone https://github.com/ennorehling/tolua-${LUA_VERSION}.git tolua
 fi
 echo "building tolua..."
 cd tolua
 make
 ARGS="$ARGS -DPC_TOLUA_DIR=$ROOT/tolua"
else
 echo "tolua is $path"
fi
unset path

set -e

cd $BIN_DIR
cmake .. $ARGS $*
cd $OLDPWD