#!/bin/sh
cd . || exit 1

. $WM_PROJECT_DIR/bin/tools/RunFunctions

rm -rf constant/polyMesh
rm -f log.gmshToFoam log.rhoPimpleFoam log.decomposePar log.reconstructPar log.checkMesh

application="$(getApplication)"

runApplication gmshToFoam airfoil.msh

python3 - <<'PY'
from pathlib import Path
import re

boundary_file = Path("constant/polyMesh/boundary")
required_types = {
    "back": "empty",
    "front": "empty",
    "Top_bot": "patch",
    "outlet": "patch",
    "inlet": "patch",
    "airfoil": "wall",
    "airfoil_slat": "wall",
    "airfoil_main": "wall",
    "airfoil_flap": "wall",
}
text = boundary_file.read_text()
for patch_name, patch_type in required_types.items():
    pattern = (rf"(^\s*{re.escape(patch_name)}\s*\n" rf"\s*\{{" rf".*?" rf"^\s*\}})")
    match = re.search(pattern, text, flags=re.MULTILINE | re.DOTALL)
    if match is None:
        print(
            f"Patch '{patch_name}' was not found in {boundary_file}"
        )
        continue
    block = match.group(1)
    block_new, n_type = re.subn(r"(^\s*type\s+)[^;]+;", rf"\g<1>{patch_type};", block, flags=re.MULTILINE)
    if n_type == 0:
        raise RuntimeError(f"Patch '{patch_name}' has no 'type' entry in {boundary_file}")
    block_new = re.sub(r"^\s*physicalType\s+[^;]+;\n", "", block_new, flags=re.MULTILINE)
    text = text[:match.start(1)] + block_new + text[match.end(1):]
boundary_file.write_text(text)
PY

checkMesh -allTopology -allGeometry | tee log.checkMesh

NP=${NP:-48}
foamDictionary system/decomposeParDict -entry numberOfSubdomains -set "$NP"
runApplication decomposePar -force
mpirun -np "$NP" rhoPimpleFoam -parallel > log.rhoPimpleFoam 2>&1
reconstructPar -latestTime
#rm -rf processor*
