#!/bin/bash

runCommand()
{
    sol=$(basename -- "$1")
    sol="${sol%.*}"
    if [ -f log."$sol" ]; then rm log."$sol"; fi
    "$@" 1> >(tee -a log."$sol") 2> >(tee -a log."$sol" >&2)
    err=$?
    if [ ! $err -eq 0 ]; then exit $err; fi
}

runParallel()
{
    nproc="$1"
    shift
    exe="$(which $1)"
    sol=$(basename -- "$1")
    sol="${sol%.*}"
    shift
    if [ -f log."$sol" ]; then rm log."$sol"; fi
    export OMPI_MCA_btl_vader_single_copy_mechanism=none  # Workaround for open-mpi/docker bug
    mpiexec  -np $nproc "$exe" -parallel "$@" 1> >(tee -a log."$sol") 2> >(tee -a log."$sol" >&2)
    err=$?
    if [ ! $err -eq 0 ]; then exit $err; fi
}

# Unset and source bashrc
if [ ! -z "$FOAMDIR" ]
then
    source "$FOAMDIR/etc/config.sh/unset" 2> /dev/null
    source "$FOAMDIR/etc/bashrc"
fi

# Extract feature edges
runCommand surfaceFeatureEdges -angle 60 "constant/triSurface/Pad_Geometry.stl" "Pad_Geometry.fms"

runCommand cartesianMesh

# Slight abuse of flattenMesh to make patch flat before extrusion
# Change patch type to empty first
cp system/changeDictionaryDict.0 system/changeDictionaryDict
runCommand changeDictionary
rm system/changeDictionaryDict
runCommand flattenMesh
cp system/extrudeMeshDict.0 system/extrudeMeshDict
# Refinement data is not processed by extrudeMesh so should be removed
rm -f constant/polyMesh/{cellLevel,pointLevel,level0Edge,refinementHistory,sets/meshProtectedCells}
runCommand extrudeMesh
mv log.extrudeMesh log.extrudeMesh.0
rm system/extrudeMeshDict


# Extract surface mesh and convert to mm for visualisation in FreeCAD
runCommand foamToSurface -scale 1000 -tri surfaceMesh.vtk
