#!/bin/sh

# Stop at first error
set -e

# Install third-party dependencies
echo "Installing ThirdParty tools"
(cd ThirdParty && ./Allwmake $* 2>&1 | tee log.Allwmake)

# Compile library
echo "Building src/wireBunchingModels"
(cd src/wireBunchingModels && ./Allwmake $* 2>&1 | tee log.Allwmake)

# Compile solvers and utilities
echo "Compiling applications/solvers/beamFoam"
(cd applications/solvers/beamFoam && wmake $* 2>&1 | tee log.Allwmake)

# Compile utilities
echo "Compiling applications/utilities"
(cd applications/utilities && wmake $* all 2>&1 | tee log.Allwmake)

# Install scripts
echo "Installing applications/scripts"
(cd applications/scripts && ./Allwmake $* 2>&1 | tee log.Allwmake)

# Check if the build succeeded
echo; echo "Checking if the installation was a success:"
N_ERRORS_1=$(find . -name log.Allwmake | xargs grep " Error " | wc -l)
N_ERRORS_2=$(find . -name log.Allwmake | xargs grep " Stop." | wc -l)
if [[ $N_ERRORS_1 -gt 0 ]] || [[ $N_ERRORS_2 -gt 0 ]]
then
    echo "** BUILD ERROR **"
    echo "There were build errors in the following logs:"
    echo $(find . -name log.Allwmake | xargs grep -l " Error ")
    echo $(find . -name log.Allwmake | xargs grep -l " Stop.")
    echo; echo "Please examine these logs for additional details"; echo
    exit 1
else
    echo "There were no build errors: enjoy beamFoam!"; echo
fi
echo
