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

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

#rm -rf 0 > /dev/null 2>&1
#cp -r 0_org 0 > /dev/null 2>&1

rm -r constant/polyMesh
rm -f log.gmshToFoam
rm -f log.foamDictionary
rm -f log.rhoPimpleFoam

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)

    # Replace existing type line.
    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}"
        )

    # Remove physicalType line if gmshToFoam wrote it.
    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

runApplication potentialFoam -writep

NP=${NP:-48}
foamDictionary system/decomposeParDict -entry numberOfSubdomains -set "$NP"
runApplication decomposePar -force