#!/bin/bash

PROJECT_URL="$1"

function usage(){
	echo "Phoenix Install provides an automatic installation script to install project in the same prefix than PhoenixCMake"
	echo "Usage :"
	echo -e "\tphoenix_install https://url/project.git"
	echo -e "\tphoenix_install https://url/project.git somebranch"
	echo -e "\tphoenix_install https://url/project.git somecommithash"
}

if [ -z "${PROJECT_URL}" ]
then
	usage
	exit -1
fi

if [[ "${PROJECT_URL}" == "-h"* ]]
then
	usage
	exit 0
fi

if [[ "${PROJECT_URL}" == "--help"* ]]
then
	usage
	exit 0
fi

if [[ "$OSTYPE" == "darwin"* ]]; then
	export nbproc=`sysctl -n hw.physicalcpu`
else
	export nbproc=`nproc`	
fi

INSTALL_PREFIX="@CMAKE_INSTALL_PREFIX@"

export PATH=$INSTALL_PREFIX/bin:$PATH
export LD_LIBRARY_PATH=$INSTALL_PREFIX/lib:$LD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=$INSTALL_PREFIX/lib:$DYLD_LIBRARY_PATH

PARENT_TMP_DIRECTORY=$PWD
TMP_PHOENIX_DIR=".phoenix_tmp"
echo "Making a temporary directory"
if [ -d ${TMP_PHOENIX_DIR} ]
then
	echo "Remove existing directory ${TMP_PHOENIX_DIR}"
	rm -fr ${TMP_PHOENIX_DIR}
fi
mkdir -p ${TMP_PHOENIX_DIR}
cd ${TMP_PHOENIX_DIR}

echo "Getting the project ${PROJECT_URL}"
git clone ${PROJECT_URL}
PROJECT_NAME=$(basename ${PROJECT_URL} | sed -e s/\.git//g)
cd ${PROJECT_NAME}

if [ ! -z $2 ]
then
	USED_BRANCH="$2"
	echo "Switching to '${USED_BRANCH}'"
	git switch ${USED_BRANCH}
fi

if [ -d build ]
then
	echo "Remove existing directory build"
	rm -fr build
fi

mkdir -p build
cd build

cmake .. -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX -DSELF_TESTS_MODE=no -DCMAKE_MODULE_PATH=${INSTALL_PREFIX}/share/cmake/Modules
if [ $? != 0 ]
then
	echo "Error on cmake : exit -1"
	exit -1
fi

make -j $nbproc
if [ $? != 0 ]
then
	echo "Error on make : exit -1"
	exit -1
fi

make install -j $nbproc
if [ $? != 0 ]
then
	echo "Error on install : exit -1"
	exit -1
fi

if [ -f $HOME/.bashrc ]; then
	source $HOME/.bashrc
fi

# Let's go to the parent directory
cd ${PARENT_TMP_DIRECTORY}
echo "Everything is OK, let's remove the temporary directory ${TMP_PHOENIX_DIR}"
rm -fr ${TMP_PHOENIX_DIR}

