#!/bin/bash
cd "${0%/*}" || exit   # Run from this directory
. "${WM_PROJECT_DIR:?}"/wmake/scripts/AllwmakeParseArguments
#------------------------------------------------------------------------------

moduleName="libWallModelledLES"

if [ "$FOAM_MODULE_PREFIX" = false ]
then
    echo "Compilation of $moduleName is disabled (prefix=false)"
    exit 0
fi

date "+%Y-%m-%d %H:%M:%S %z" 2>/dev/null || echo "date is unknown"
echo "Starting compile of $moduleName"
echo "  $WM_COMPILER $WM_COMPILER_TYPE compiler"
echo "  ${WM_OPTIONS}, with ${WM_MPLIB} ${FOAM_MPI}"
echo "  prefix = ${FOAM_MODULE_PREFIX:-default (user)}"
echo


unset prevVersion
if [ -e foamVersionThisIsCompiledFor ]
then
    prevVersion=$(<foamVersionThisIsCompiledFor)
fi

if [ -n "$prevVersion" ]
then
    if [ "$prevVersion" = "$WM_PROJECT_VERSION" ]
    then
        echo "  Rebuilding for OpenFOAM = $WM_PROJECT_VERSION ($FOAM_API)."
        echo
    else
        echo "  Previously compiled for OpenFOAM = $prevVersion"
        echo "  but now using OpenFOAM = $WM_PROJECT_VERSION ($FOAM_API)."
        echo "     Use ./Allwclean before compiling"
        echo
        exit 42
    fi
else
    echo "  Building for OpenFOAM = $WM_PROJECT_VERSION ($FOAM_API)."
    echo
    echo "${WM_PROJECT_VERSION:-unknown}" >| foamVersionThisIsCompiledFor
fi

versionFile=versionRules/foamVersion4wmles.H

if versionRules/createVersionRules.sh >| "$versionFile.tmp"
then
    :  # Generated with script from WM_PROJECT_DIR information
else
    # Fallback to python and generate from WM_PROJECT_VERSION information
    versionRules/makeFoamVersionHeader.py $WM_PROJECT_VERSION >| $versionFile.tmp
fi


if [ -e "$versionFile" ]; then
    nrDiff=$(diff $versionFile.tmp $versionFile | wc -l | tr -d " ")
    if [[ $nrDiff > 0 ]]; then
    echo "$versionFile changed"
    mv $versionFile.tmp $versionFile
    else
    # Make sure that not a complete recompilation is triggered
    echo "No change to $versionFile"
    rm -f "$versionFile.tmp"
    fi
else
    echo "No $versionFile. Generating!"
    mv $versionFile.tmp $versionFile
fi

# Ensure consistent definition of OPENFOAM_COM without relying anything else.
# This may be available from the regular wmake rules, but use our own convention
sed -ne 's/.*WMLES_IS_COM \([0-9][0-9]*\)/OPENFOAM_COM=\1/p' < $versionFile >| versionRules/foamVersion
sed -ne 's/.*WMLES_IS_ORG \([0-9][0-9]*\)/OPENFOAM_ORG=\1/p' < $versionFile >> versionRules/foamVersion


echo
echo "  Please include the output above when reporting a problem in the compilation. It helps diagnosing the problem    "
echo

wmake libso

#------------------------------------------------------------------------------
