#!/bin/bash
#cd ${0%/*} || exit 1    # Run from this directory

#rm ./log.*
# Abort the script on error
#set -euxo pipefail
set -euo pipefail
#set -e pipefail

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

# Without this, only stdout would be captured - i.e. your
# log file would not contain any error messages.

# exec | 2> /dev/stderr
#exec || (>&2 echo "Command returned an error!"; logHeader "END ON ERROR")

# Find the scripts to call.  Try to locate in case directory, otherwise use default pyFoamd files
for script in Allrun Allmesh AllmeshCf postProcess reconstructMesh
do
    if [ -f "$script" ]; then
        cp ${PWD}/$script /tmp/$script
        sed -i -e 's@cd ${0%/*}@@g' /tmp/$script
        eval "script$script='/tmp/$script'"
    else
        eval "script$script='$(dirname "$0")/../bash/$script'"
    fi
done

# Determine if the OpenFOAM enviornment is set
if [ -z ${WM_PROJECT_VERSION+x} ];
then
  echo "ERROR: OpenFOAM not found!"
  exit 1
fi

# 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
foamVersion=$(echo $WM_PROJECT_VERSION | sed 's/[^0-9]*//g')  #remove non-numeric characters
if [[ $foamVersion -le 7 ]];
then
  . $SCRIPT_DIR/../bash/RunFunctionsv7 #Prints log to stdout AND the log.* file
else
  . $SCRIPT_DIR/../bash/RunFunctions #Prints log to stdout AND the log.* file
fi

logHeader "START"

echo "Running command:" $0 $@

runSim=true
runMesh=true
cfMesh=false
improveMesh=false
reconstructSim=false
runCommand=runApplication
restartSim=false
justSolve=false
clearLogs=false
postProcess=false
topoSet=false
forceDecompose=false


searchDir="processor0"
if [ ! -d "$searchDir" ]; then
  decomposed="false"
  echo "The case is not decomposed."
else
  decomposed="true"
  echo "The case is decomposed."
fi

#- Parse command arguments
PARAMS=""

while (( "$#" )) ; do
case "$1" in
#while [[ $# -gt 0 ]]
#do
#    key="$1"
#    case $key in
#for i in "$@"
#do
#case $i in
    -parallel) #run in parallel
        runCommand=runParallel
        shift
        ;;
    -meshOnly) #run meshing commands only
        runSim=false
        shift
        ;;
    -cfMesh) #use cfMesh library for meshing instead of snappyHexMesh
        cfMesh=true
        nImproveCycles=$2
        shift 2
        ;;
    -improveMesh) #just run the improveMeshQuality application
        improveMesh=true
        shift
        ;;
    -reconstruct) #reconstruct the simulation after completion
        reconstructSim=true
        shift
        ;;
    -restart) #restart an existing simulation
        restartSim=true
        runMesh=false
        shift
        ;;
    -decomposed) #restart a case from a decomposed state
        decomposed=true
        runMesh=false
        shift
        ;;
    -forceDecompose) #run decomposePar with the '-force' option
        forceDecompose=true
        shift
        ;;
    -noMesh) #run without meshing
        runMesh=false
        shift
        ;;
    -justSolve) #run the solver and nothing else
        justSolve=true
        shift
        ;;
    -clearLogs) # delete all of the existing 'log.*' files
        clearLogs=true
        shift
        ;;
    -postProcess) # run the "postProcess" commands
        postProcess=true
        shift
        ;;
    -justPostProcess) # run the "postProcess" commands, and do nothing else
        postProcess=true
        justSolve=false
        runMesh=false
        runSim=false
        reconstructSim=false
        shift
        ;;
    -withTopoSet)
        topoSet=true
        shift
        ;;
    -*|--*)
        echo "Invalid option $1" >&2

        exit 1
        ;;
    *)
        PARAMS="$PARAMS $1"
        shift
        ;;
esac
done
#shift $((OPTIND -1))

eval set -- "$PARAMS"

promptUser () {
    msg=$1
    cmd=$2
    while true; do
        read -p "$msg" yn
        case $yn in
            [Yy]* ) eval "$cmd";;
            [Nn]* ) exit;;
            * ) echo "Please answer 'yes' or 'no'.";;
        esac
    done
}

runDecompose () {
    if [ -f log.decomposePar ];
    then
        promptUser "decomposePar log already exists. Overwrite?" "rm -f log.decomposePar"
    fi
    if [ -d processor0 ];
    then
        promptUser "Case is already decomposed.  Remove existing case?" "promptUser 'Are you sure?  Simulation data will be deleted' 'rm -rf processor*'"
    fi

    runApplication decomposePar
}


if [ "$clearLogs" = true ]
then
    rm log.*
fi


NPROCS=getNumberOfProcessors

export NPROCS
{

if [ "$improveMesh" = true ]
then

  $runCommand improveMeshQuality

elif [ "$justSolve" = true ]
then

  if [ "$runCommand" = "runParallel" ] && [ "$decomposed" = false ] || [ "$forceDecompose" = true ];
  then
      runApplication decomposePar
  fi


  $runCommand $(getApplication)

else
    if [ "$runMesh" = true ]
    then
        if [ "$cfMesh" = true ]
        then
            runScript $scriptAllmeshCf
        else
            runScript $scriptAllmesh
        fi
    fi

    if [ "$runSim" = true ]
    then
        runScript $scriptAllrun
    fi

    if [ "$reconstructSim" = true ]
    then
        runScript $scriptreconstructMesh
    fi

    if [ "$postProcess" = true ]
    then
        runScript $scriptpostProcess
    fi
fi

}
#runApplication reconstructParMesh -mergeTol 1E-06 -constant
#runApplication reconstructPar -latestTime -withZero
#rm -rf ./processor*
#
#runApplication -a decomposePar -copyZero -force
#
#rm log.potentialFoam
#$runCommand potentialFoam
#
#rm log.$(getApplication)
#$runCommand $(getApplication)
#
#if [  ];
#then
#  if [[ $runCommand == "runParallel" && reconstructSim == true ]];
#  then
#    runApplication reconstructParMesh -mergeTol 1E-06 -constant
#
#    runApplication reconstructPar -constant
#  fi
#fi

logHeader "END"
#------------------------------------------------------------------------------
