#!/bin/bash

#
# Script to build libtqtvd_astronav.so
#
# Autor: Mirakulo Software
#
#

if [[ -z "${SETENV_SOURCED}" ]] && [[ -e ${CONFIGSROOT}/setenv.sh ]]; then
	source ${CONFIGSROOT}/setenv.sh
fi

if [ -z $BUILD_JOBS ]; then
	BUILD_JOBS=4
	export BUILD_JOBS
fi

BUILD_DIR_PREFIX=

if [ -z $CMAKE_EXEC ];then
  echo "Failed to find cmake from /work/sdk/common"
  exit 1
fi

if [ ! -z $CMAKE_EXEC_OPTS ];then
  echo "Using extra options in cmake ($CMAKE_EXEC_OPTS)"
  CMAKE_EXEC="$CMAKE_EXEC $CMAKE_EXEC_OPTS"
fi

echo "Parallel build jobs $BUILD_JOBS"

CMAKELISTS=$(pwd)

doBuild()
{
    BUILDDIR="$BUILD_DIR_PREFIX""$2"
    mkdir -p $BUILDDIR
    pushd "$BUILDDIR" > /dev/null
    if [ $? != 0 ]; then
		echo "Invalid build dir: $BUILDDIR"
        exit 3;
    else
        echo "Build dir is  $BUILDDIR"
    fi

	rm -f CMakeCache.txt
	
	CMAKE_ARGS="-Wno-dev $CMAKE_IDE_PROJECT -DTQTVD_PLATFORM:STRING=$1 -DCMAKE_BUILD_TYPE:STRING=Custom -DCMAKE_TOOLCHAIN_FILE=$3 -DCMAKE_INSTALL_PREFIX:STRING=$4  -DTQTVD_DEBUG_ENABLED:STRING=$5 -DTARGET_PREFIX=$6"
	if [ -n "$TQTVD_TARGET" ]; then
		CMAKE_ARGS+=" -DTQTVD_TARGET:STRING=${TQTVD_TARGET}"
	fi
	if [ "$RELEASE_VERSION" == "YES" ]; then
		CMAKE_ARGS+=" -DRELEASE_VERSION:STRING=_"
	fi
	CMAKE_ARGS+=" $8 $9 ${10} $CMAKELISTS"
	
	echo CMAKE_ARGS "($CMAKE_ARGS)"
	
	$CMAKE_EXEC $CMAKE_ARGS
	
	if [ "x${VERBOSE_SCRIPTS}" != "x" ]; then
		make VERBOSE=1 -j$BUILD_JOBS install
	else
		make -j$BUILD_JOBS install
	fi
    ok=`echo $?`
    popd > /dev/null
}

doBuild ${TQTVD_TARGET} ./build/release ${CONFIGSROOT}/Toolchain.cmake $(pwd) 0 TARGET_STUB stub

NOTIFY=/usr/bin/notify-send
if [ -e $NOTIFY ]; then
  if [ "$ok" == 0 ]; then
    notify_message="Build '$BUILDTYPE' finalizado"
    notify_type=info
    $NOTIFY --hint=int:transient:1 -h int:x:1060 -h int:y:20 -i $notify_type "${TQTVD_TARGET}" "$notify_message"
    exit 0 ;
  else
    notify_message="Build '$BUILDTYPE' finalizado com erros"
    notify_type=error
    $NOTIFY --hint=int:transient:1 -h int:x:1060 -h int:y:20 -i $notify_type "${TQTVD_TARGET}" "$notify_message"
    exit 1 ;
  fi
else
  echo "##########################################################"
  if [ "$ok" == 0 ]; then
    notify_message="Build '$BUILDTYPE' finalizado"
    echo "$notify_message"
    echo "##########################################################"
    exit 0 ;
  else
    notify_message="Build '$BUILDTYPE' finalizado com erros"
    echo "$notify_message"
    echo "##########################################################"
    exit 1 ;
  fi
fi
