#! /bin/bash

#mk Output folders
mkdir -p  outputs/settings
mkdir -p  outputs/quantitative
mkdir -p  outputs/genotypes

#mk Compile folders
mkdir -p sources/obj
mkdir -p sources/bin


#platform='unknown'
#unamestr=$(uname)
#echo $unamestr
#if [[ "$unamestr" -eq "Linux" ]]; then
#   platform='linux'
#elif [[ "$unamestr" -eq "Cygwin_NT-6.1" ]]; then
#   platform='posix'
#else
#    echo "Platform $(unamestr) not recognized"
#fi

if (( $# != 1 )); then
    echo "Platform (linux or posix) must be defined as argument."
    exit 1
fi

platform=$1 #TODO: Need to be tested and documented

rm sources/lua-5.3.0 -r
#Check lua folder
#if [ ! -d sources/lua-5.3.0 ]; then
#echo "Lua folder not found... restoring from lua-5.3.0.tar.gz"
echo "Extracting Lua from lua-5.3.0.tar.gz..."
cd sources
tar -xzf lua-5.3.0.tar.gz
if (( $? != 0 )); then
    echo "Error during extraction, program aborted. Installation has failed."
    exit 1
fi

cd ..
#fi

#Check if lua compiled
#if [ ! -e sources/lua-5.3.0/src/liblua.a ]; then
    #Check lua folder
    #echo "liblua.a not found, compiling lua..."
echo "Compiling Lua..."
cd sources/lua-5.3.0
make $platform #linux or posix
if (( $? != 0 )); then
    echo "Error during lua compilation, program aborted. Installation has failed."
    exit 1
fi


make test
cd ../..

#Compiling metapop
echo "Compiling metapop"
cd sources
rm obj/*.o
make
if (( $? != 0 )); then
    echo "Error during MTP compilation, program aborted. Installation has failed."
    exit 1
fi



cd ..

#Check if all R libraries are installed
echo "Check if MCMCpack (R module) needs to be installed. May take a while."
R CMD BATCH checkpackages.r
if grep -q "Markov Chain" checkpackages.r.Rout
then
    echo "MCMCpack installed"
    rm checkpackages.r.Rout
    echo "Installation is completed"
else
    echo "MCMCpack (R module) NOT installed. Installation aborted."
fi


