#!/bin/bash

# Author: Lukas Maier
# Affiliation: Institute of Process and Particle Engineering, TU Graz
# License: LGPL 3.0

# Set number of processors
nprocessors=4

# Set LIGGGHTS executable path
LIGGGHTS_EXEC=liggghts-maiergibowsky
# Function to delete subfolders
cleanup_subfolders() {
    rm -rf post_sphere post_forces post_fill post_clemmer
}

# Cleanup previous runs
cleanup_subfolders

# Create log directory
mkdir -p log

vel=0.003

# Read JSON output
output_file="data/output.json"
if [[ -f "$output_file" ]]; then
    json_content=$(cat "$output_file")
    output1=$(echo "$json_content" | grep -oP '(?<=\[)[^,]+' | sed -e 's/"//g')
    output2=$(echo "$json_content" | grep -oP '(?<=,)[^,\]]+' | sed -e 's/"//g')
    echo "Output1: $output1"
    echo "Output2: $output2"
else
    echo "Error: Output file not found!"
    exit 1
fi

# Run first insertion stage
if [[ ! -f restart/insertedParticles1.restart ]]; then
    ${LIGGGHTS_EXEC} -var vertexradius ${output1} \
        -var edgelength ${output2} -in system/ins.in -log log/ins.log
else
    echo "insertedParticles1.restart file found in restart-folder. Skipping this step."
fi

# Run second insertion stage
if [[ ! -f restart/insertedParticles.restart ]]; then
    mpirun -np ${nprocessors} ${LIGGGHTS_EXEC} -var vertexradius ${output1} \
        -var edgelength ${output2} -in system/ins2.in -log log/ins2.log
else
    echo "insertedParticles.restart file found in restart-folder. Skipping this step."
fi

# Extract maximum coordinate

if [[ ! -f restart/insertedParticles_clemmer.restart ]]; then
    eval $(python3 scripts/extraction_allcoordinates.py)
    echo "Maximum Coordinate: $MAX_ABS_COORD"
    mpirun -np ${nprocessors} ${LIGGGHTS_EXEC} -var vertexradius ${output1} \
        -var edgelength ${output2} -var MAX_ABS_COORD ${MAX_ABS_COORD} \
		-in system/sphere_spring.in -log log/sphere_spring.log
else
    echo "insertedParticles_clemmer.restart file found in restart-folder. Skipping this step."
fi
# Extract adjusted max and min z values
eval $(python3 scripts/extraction.py)

# Validate MAX_Z and MIN_Z
if ! [[ "$MAX_Z" =~ ^-?[0-9]+([.][0-9]+)?$ ]] || ! [[ "$MIN_Z" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
    echo "Error: MAX_Z or MIN_Z is not a valid number."
    exit 1
fi

echo "Adjusted Maximum Z: $MAX_Z"
echo "Adjusted Minimum Z: $MIN_Z"

# Final LIGGGHTS run with adjusted parameters
mpirun -np ${nprocessors} ${LIGGGHTS_EXEC} \
    -var vertexradius ${output1} \
    -var edgelength ${output2}  -var MIN_Z ${MIN_Z} -var MAX_Z ${MAX_Z}\
	-var vel ${vel} -in system/compaction.in -log log/compaction.log

# Create finished.txt to indicate successful completion
echo "Simulation completed successfully on $(date)" > finished.txt
echo "Simulation completion marker (finished.txt) created."





