#!/bin/bash

# Enable recursive globbing (for **)
shopt -s globstar

# Get the target directory from the first argument
TARGET_DIR="$1"
LOG_FILE="rename_log_$(date +%Y-%m-%d).txt"

# --- Function to log messages to both console and log file ---
log_message() {
    echo "$1" | tee -a "$LOG_FILE"
}

# --- Main Script Logic ---

# Check if a directory path was provided
if [ -z "$TARGET_DIR" ]; then
    log_message "[ERROR] No directory specified. Usage: ./add_ext.sh /path/to/your/images"
    exit 1
fi

# Check if the provided path is a valid directory
if [ ! -d "$TARGET_DIR" ]; then
    log_message "[ERROR] Directory '$TARGET_DIR' not found."
    exit 1
fi

log_message "--------------------------------------------------"
log_message "Starting RECURSIVE image extension script on $(date)"
log_message "Target Directory: $TARGET_DIR"
log_message "Log File: $LOG_FILE"
log_message "--------------------------------------------------"

# Loop through every item in the target directory and all subdirectories
for file in "$TARGET_DIR"/**/*; do
    # Check if the item is a regular file and not a directory
    if [ -f "$file" ]; then
        filename=$(basename "$file")

        # Check if the filename does NOT contain a dot ('.')
        if [[ "$filename" != *.* ]]; then
            # If no dot, it has no extension. Rename it.
            log_message "[RENAME] '$file' -> '$file.jpg'"
            mv "$file" "$file.jpg"
        else
            # If it has a dot, skip it.
            log_message "[SKIP] '$file' already has an extension."
        fi
    fi
done

log_message "--------------------------------------------------"
log_message "Script finished successfully."
log_message "--------------------------------------------------"
