#!/bin/sh
#------------------------------------------------------------------------------
# =========                 |
# \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
#  \\    /   O peration     |
#   \\  /    A nd           | www.openfoam.com
#    \\/     M anipulation  |
#------------------------------------------------------------------------------
#     Copyright (C) 2011-2016 OpenFOAM Foundation
#     Copyright (C) 2018-2019 OpenCFD Ltd.
#------------------------------------------------------------------------------
# License
#     This file is part of OpenFOAM, licensed under GNU General Public License
#     <http://www.gnu.org/licenses/>.
#
# Script
#     foamRunTutorials
#
# Description
#     Run either Allrun or blockMesh/application in current directory
#     and all its subdirectories.
#
#     For tutorials that are known to run poorly, an Allrun-optional
#     placeholder can be used instead of the usual Allrun script.
#     When this is detected, the case will be skipped.
#
#------------------------------------------------------------------------------
. ${WM_PROJECT_DIR:?}/bin/tools/RunFunctions    # Tutorial run functions

# Normally use standard "make"
make="make"

thisScript="$0"
if [ "/${thisScript#/}" != "$thisScript" ]
then
    thisScript="$PWD/$thisScript"
fi

unset passArgs runTests skipFirst

# Parse options
while [ "$#" -gt 0 ]
do
    case "$1" in
    -t | -test)
        passArgs="-test"
        runTests=true
        ;;

    # Avoid infinite recursion when invoked from an Allrun or Alltest script
    -s | -skipFirst)
        skipFirst=true
        ;;
    *)
        break
        ;;
    esac
    shift
done

if [ -z "$skipFirst" ] && [ -n "$runTests" ] && test -f Alltest
then
    # Run specialized Alltest script
    ./Alltest $passArgs $*
elif [ -z "$skipFirst" ] && test -f Allrun
then
    # Run specialized Allrun script
    ./Allrun $passArgs $*
elif [ -z "$skipFirst" ] && test -f Allrun-optional
then
    # Has Allrun-optional script - skip this tutorial.
    echo "Skipped optional case $PWD"
elif [ -d system ]
then
    # Run normal case with blockMesh and the application
    runApplication blockMesh
    runApplication $(getApplication)
else
    # Loop over sub-directories and compile any applications
    for caseName in *
    do
        if [ -d "$caseName" ] && [ -d "$caseName/Make" ]
        then
            ( compileApplication "$caseName" )
        fi
    done
    FOAM_TARGETS=$(for d in *; do [ -d "$d" ] && echo "$d"; done | xargs)

    # Run all cases which have not already been run
    $make -k -f $WM_PROJECT_DIR/bin/tools/MakefileDirs \
          FOAM_TARGETS="$FOAM_TARGETS" \
          FOAM_APP="$thisScript" FOAM_ARGS="$passArgs $*"
fi

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