#!/bin/sh
cd "${0%/*}" || exit                                # Run from this directory
. ${WM_PROJECT_DIR:?}/bin/tools/RunFunctions        # Tutorial run functions
#------------------------------------------------------------------------------

# 1) First run steady-state to establish a good initial field.
# 2) Copy the latest state-state results for the transient case,
#    but need to copy the pointDisplacement from the 0/ directory
#    since it will not have been used for the steady-state case
# 3) Relocate this initial solution to coincide with the first deltaT
#    to avoid overwriting the 0/ directory at all.

#
# copyParallelPointDisplacement caseDir timeName
#
# Copy pointDisplacement from caseDir/0/ to caseDir/timeName/
#
copyParallelPointDisplacement()
{
    local src=$1
    local dstTime=$2
    local file=pointDisplacement

    [ -d "$src" ] || {
        echo "Error: no directory: $src"
        return 1
    }

    # Copy select directories
    echo "    copy processor '$file' from 0/ -> $dstTime"
    if [ -n "$dstTime" ]
    then
    (
        cd "$src" || exit

        for proc in processor*
        do
            [ -d "$proc/0" -a -d "$proc/$dstTime" ] && \
                cp $proc/0/$file $proc/$dstTime/$file
        done
    )
    else
        echo "    no destination time"
    fi

    # Restart from latestTime
    foamDictionary $src/system/controlDict \
        -entry startFrom -set latestTime

    deltaT=$(foamDictionary $src/system/controlDict -entry deltaT -value)
    latestTime=$(foamListTimes -case $src -noZero -latestTime -processor)

    # Restart using steady results as first deltaT interval
    echo "deltaT=$deltaT latestTime=$latestTime"
    if [ -n "$latestTime" -a "$deltaT" != "$latestTime" ]
    then
    (
        cd "$src" || exit

        for proc in processor*
        do
            if [ -d "$proc/$latestTime" -a ! -d "$proc/$deltaT" ]
            then
                mv $proc/$latestTime $proc/$deltaT
                rm -rf "$proc/$deltaT/uniform"
            fi
        done
    )
    fi

    return 0
}


# Do steady-state case
(cd steady && foamRunTutorials)

if notTest $@
then
    latestTime=$(\cd steady && foamListTimes -noZero -latestTime -processor)

    # Clone the steady-state case to transient
    cloneParallelCase steady transient 0 $latestTime

    copyParallelPointDisplacement transient $latestTime

    # Adjust application (from simpleFoam -> pimpleFoam)
    foamDictionary transient/system/controlDict \
        -entry application -set pimpleFoam

    # Do the transient case
    \cp files/Allrun.transient transient/Allrun
    (\cd transient && foamRunTutorials)
fi

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