#!/bin/bash

# Abort the script on error
#set -euxo pipefail
set -euo pipefail
#set -e pipefail

# Redirect stdout ( > ) into a named pipe ( >() ) running "tee"
#exec >> Log

# Source tutorial run functions
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
. $WM_PROJECT_DIR/bin/tools/RunFunctions #Prints log to the log.* file only
. $SCRIPT_DIR/../bash/RunFunctions #Prints log to stdout AND the log.* file


logHeader "START" >> Log

echo "Running command:" $0 $@ >> Log

for d in ./*; do
    if [ -d "$d" ]; then
        echo "Processing directory $d..."
        cd $d
        exec | tee -a Log 
        if [ "$(isCase)" == "true" ];
        then
            logHeader "START"
            foamDictionary -entry writeFormat -set binary system/controlDict
            if [ "$(isDecomposed)" == "true" ];
            then
                runParallel -o foamFormatConvert
            fi
            if [ "$(isReconstructed)" == "true" ];
            then
                if [ -f constant/polyMesh/points ]; then #TODO Create "isMeshed()" function
                    runApplication -o foamFormatConvert
                else
                    echo "No mesh found for case $d."
                fi
            fi
        else
            echo "$d is not an OpenFOAM case."
        fi
        logHeader "END"
        cd ../
    fi
done


exec >> Log

logHeader "END"
