#!/bin/sh

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

# Source tutorial run functions
. "$WM_PROJECT_DIR/bin/tools/RunFunctions"

usage () {
    exec 1>&2
    while [ "$#" -ge 1 ]; do echo "$1"; shift; done
    cat <<USAGE

Usage: ${0##*/} [OPTIONS]
options:
  -c | -cores <nCores>   number of cores in parallel run
  -h | -help             help
  -m | -mesh <S|M|L|XL>  mesh size
                         - S: small, 440k cells
                         - M: medium, 3M cells (default)
                         - L: large, 22.5M cells
                         - XL: extra large, ~200M cells

Runs the ${PWD##*/} simulation

USAGE
    exit 1
}

checkCores () {
    _cores="$1"

    ! [ "$_cores" -eq "$_cores" ] 2> /dev/null && \
        echo "Number of cores '$_cores' must be an integer" && \
        return 1

    [ "$_cores" -lt 2 ] && \
        echo "Number of cores '$_cores' must be >= 2" && \
        return 1

    return 0
}

refineBackgroundMesh () {
    _nRefine="$1"
    _r=0
    while [ $_r -lt "$_nRefine" ]
    do
        echo "Refining the background mesh"
        runParallel -a refineMesh -overwrite
        _r=$(( _r + 1 ))
    done
}

setKeyword () {
    _entry="$1"
    _value="$2"
    _file="$3"

    foamDictionary -entry "$_entry" -set "$_value" "$_file" > /dev/null
}

nRefine=1
nCores=8

while [ "$#" -gt 0 ]
do
   case "$1" in
   -c | -cores)
      [ "$#" -ge 2 ] || usage "'$1' option requires an argument"
      nCores=$2
      shift 2
      checkCores "$nCores" || usage
      setKeyword numberOfSubdomains "$nCores" system/decomposeParDict
      ;;
   -h | -help)
      usage
      ;;
   -m | -mesh)
      [ "$#" -ge 2 ] || usage "'$1' option requires an argument"
      mesh=$2
      shift 2
      case "$mesh" in
          S)  ;;
          M)  nRefine=1 ;;
          L)  nRefine=2 ; setKeyword endTime 2000 system/controlDict ;;
          XL) nRefine=3 ; setKeyword endTime 2000 system/controlDict ;;
          *)  usage "Invalid argument '$mesh' to -m|-mesh <S|M|L|XL>." ;;
      esac
      ;;
   -test)
      shift
      ;;
   -*)
      usage "Invalid option '$1'"
      ;;
   *)
      break
      ;;
    esac
done

# START OF MAIN SCRIPT

runApplication blockMesh

runApplication decomposePar -copyZero

refineBackgroundMesh $nRefine

# echo "Switching to ptscotch for dynamic load balancing with snappyHexMesh"
# setKeyword method ptscotch system/decomposeParDict

runParallel snappyHexMesh -overwrite

runParallel checkMesh

runParallel "$(getApplication)"

# runApplication reconstructParMesh -constant
# runApplication reconstructPar -latestTime

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