#!/bin/bash

MESHES=("blunt_body.msh" "spiked_blunt_body.msh")

# Check if any of the mesh files exist
found=false

for MESH in "${MESHES[@]}"; do
    if [ -f "$MESH" ]; then
        found=true
        break
    fi
done

if [ "$found" = false ]; then
    echo "Error: No .msh files were found!"
    exit 1
fi

# Convert the Fluent mesh to OpenFOAM format
if [ ! -f "spiked_blunt_body.msh" ]; then
    fluent3DMeshToFoam "blunt_body.msh"
else
    fluent3DMeshToFoam "spiked_blunt_body.msh"
fi

# Change the dictionary files in boundary in polymesh folder from walls to patch
changeDictionary

# Check if decomposeParDict exists, and if not, create it
if [ ! -f system/decomposeParDict ]; then
    decomposePar -force
fi

# Decompose the case
decomposePar

# Run the simulation in parallel and use pyFoamPlotRunner to generate plots
pyFoamPlotRunner.py mpirun -np 5 sonicFoam -parallel

# Reconstruct the case after simulation completion
reconstructPar

# Remove processor directories
rm -rf processor*

# Create the 'pyfoam' directory if it doesn't exist
mkdir -p pyfoam

# Move files starting with 'PyFoam' to the 'pyfoam' directory
mv PyFoam* pyfoam/ 2>/dev/null

# Move the 'Gnuplotting.analyzed' folder to the 'pyfoam' directory
mv Gnu* pyfoam/ 2>/dev/null

# Run parafoam
paraFoam
