#!/usr/bin/env bash

# Define the working directory
WORKING_DIR="/path/to/your/files"

# Change to the working directory
cd "$WORKING_DIR" || echo "Could not change to directory: $WORKING_DIR" && exit 1

# Define a loop counter
COUNTER=1

while IFS= read -r FILE
    do
        # Store the directory of the file
        DIR=$(dirname "$FILE" | tr '[:upper:]' '[:lower:]')

        # Strip the file extension and convert to lowercase
        OLD_NAME=$(basename "$FILE" | sed 's/\.txt$//' | tr '[:upper:]' '[:lower:]')

        # Rename the file with a new name based on the counter
        NEW_NAME=$("${OLD_NAME}_${COUNTER}.txt")

        # Perform the renaming
        if mv "${DIR}/${OLD_NAME}" "${DIR}/${NEW_NAME}"
            then
                # Output the success message
                echo "Renamed '${DIR}/${OLD_NAME}' '${DIR}/${NEW_NAME}'"
                
                # Increment the counter
                COUNTER=$((COUNTER + 1))
            else
                # Output the failure message
                echo "Failed to rename '$FILE'"

                # Exit the script with an error status
                exit 1
        fi
    done < <(find . -type f -name "*.txt" | sort -u)

# $ shellcheck No issues detected!
