#!/bin/bash
#-----------------------------------------------------------------
# This script formats the LMDZ fortran routines with
# a common and unified format
# it works in 1 or 2 steps:
# 1/an optional preprocessing step with findent (if_findent) 
# (more robust for code structuration)
# 2/a formatting step with fprettify using a .fprettify format file
#
# if findent or fprettify displays an error or warning message,
# the file is not processed
# how to use:
# ./format_code.sh "file1 file2 file3"
# v1: November 2025
#-----------------------------------------------------------------


# List of files to process
#------------------------------------------------------------------
#files_to_process=( $(find ../libf/*/*blowing* -maxdepth 0 -type f ! -xtype l \( -name "*.f90" -o -name "*.F90" \)) )

files_to_process="$1"

# Check installation of findent and fprettify 
#------------------------------------------------------------------
if command -v findent >/dev/null 2>&1; then
    echo "findent has been installed"
    findent --version
else
    echo "findent has not been installed"
    echo "please install it with sudo apt-get install findent"
fi


if command -v fprettify >/dev/null 2>&1; then
    echo "fprettify has been installed."
    fprettify --version
else
    echo "fprettify has not been installed."
    echo "please install it with: pip install fprettify"
fi

# write the .fprettify configuration file
#------------------------------------------------------------------
FILENAME=".fprettify"

# check if the .fprettify exists
if [ -f "$FILENAME" ]; then
    echo "the file $FILENAME already exists"
else
echo "I create the file $FILENAME "

# create the file
cat << 'EOF' > "$FILENAME"
# =========================
# fprettify configuration
# =========================

# Indentation (number of spaces)
indent = 3

# Maximum line length
line-length = 200

# Indent internal blocks (do, if, select case…)
indent-blocks = true

# Add whitespace around operators (=, +, -, *, /, etc.)
whitespace = true

# Keyword normalization (lowercase or uppercase)
case = [2,2,2,2]

# Reformat declarations (type :: variable)
reformat-declarations = true

# Align variable declarations
align-declarations = true

# Align consecutive assignments
align-assignments = true

# Align arguments in multi-line calls
align-arguments = true

# Preserve comments as-is
preserve-comments = true

# Do not modify string literals
preserve-strings = true

# Reformat line continuations (&)
reformat-continuations = true

# Reformat USE statements
reformat-use-statements = true

# Allow inline formatting control
# (via ! fprettify: off / on)
enable-inline-control = true
EOF
fi

# formatting step
#------------------------------------------------------------------
# Array to store files that could not be processed
failures=()

# Function that applies findent and fprettify to a file
# with checks on errors and warnings

process_file() {
    local f="$1"
    local tmp
    tmp=$(mktemp) || return 1

    local patterns="error"
    local err
    local ret

    cp "$f" "$tmp"

# Step 1: findent
    if_findent=0
    if [ "$if_findent" -eq 1 ]; then
       rm "$tmp"
       err=$(findent < "$f" 2>&1)
       ret=$?
       if [ $ret -ne 0 ] || echo "$err" | grep -Eqi "$patterns"; then
          echo "findent detected ERROR in $f"
          echo $err
	  #rm -f "$tmp"
          return 1
       fi
       findent < "$f" > "$tmp" 2>/dev/null
    fi

# Step 2: fprettify
    err=$(fprettify  "$tmp" 2>&1)
    ret=$?
    if [ $ret -ne 0 ] || echo "$err" | grep -Eqi "$patterns"; then
        echo "fprettify detected ERROR in $f"
        echo "$err"   
	#rm -f "$tmp"
        return 1
    fi

    # Step 3: replace original file
    mv "$tmp" "$f"
    return 0
}


# Loop over all the files that we want to process
for f in "${files_to_process[@]}"; do
    echo "Processing $f ..."

    if process_file "$f"; then
        echo "ok"
    else
	echo "failure"
        failures+=("$f")
    fi
done

# Summary report
echo
echo "========== SUMMARY =========="
if [ ${#failures[@]} -eq 0 ]; then
    echo "All files were processed successfully."
else
    echo "The following files could NOT be processed:"
    for f in "${failures[@]}"; do
        echo " - $f"
    done
fi


