#!/usr/bin/env bash

set -euo pipefail
shopt -s nullglob

step1_only=0
if [[ "${1:-}" == "--step1-only" ]]; then
    step1_only=1
fi

case_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"

if [[ ! -f "$case_dir/system/controlDict" || ! -d "$case_dir/0_org" ]]; then
    echo "Error: invalid OpenFOAM case directory: $case_dir" >&2
    exit 1
fi

# Step 1: wipe everything except the case setup (system/, constant/, 0_org/)
# and the run scripts themselves.
keep=(system constant 0_org clean.sh run_all.sh run_mesh.sh run_sim.sh log 30N30P.foam)
for entry in "$case_dir"/* "$case_dir"/.[!.]*; do
    [[ -e "$entry" ]] || continue
    name="${entry##*/}"
    is_kept=0
    for k in "${keep[@]}"; do
        [[ "$name" == "$k" ]] && is_kept=1 && break
    done
    [[ "$is_kept" -eq 1 ]] || rm -rf -- "$entry"
done

# Within log/, only the mesh-related logs survive step 1.
if [[ -d "$case_dir/log" ]]; then
    log_keep=(generateMesh2D checkMesh)
    for entry in "$case_dir"/log/*; do
        [[ -e "$entry" ]] || continue
        name="${entry##*/}"
        is_kept=0
        for k in "${log_keep[@]}"; do
            [[ "$name" == "$k" ]] && is_kept=1 && break
        done
        [[ "$is_kept" -eq 1 ]] || rm -rf -- "$entry"
    done
fi

echo "Simulation clean"

if [[ "$step1_only" -eq 1 ]]; then
    echo "Case cleaned (step 1 only): $case_dir"
    exit 0
fi

# Step 2: optionally reset the mesh too.
answer=""
read -r -p "Also clean the mesh (delete constant/polyMesh)? [y/N] " answer || answer="n"
if [[ "$answer" =~ ^[Yy]$ ]]; then
    rm -rf -- "$case_dir/constant/polyMesh" "$case_dir/log"
    echo "Mesh clean"
else
    echo "Mesh kept."
fi

echo "Case cleaned: $case_dir"
