#!/bin/bash
current_date=$(date +'%Y-%m-%d')
chafa_settings="-c 240 --color-space din99d --dither ordered --symbols -space -s 128 --fg-only"

read -p "Enter gallery name or leave blank to use the current date ('$current_date'): " gallery_name_input
if [ -z "$gallery_name_input" ]; then
    gallery_name="$current_date"
else
    gallery_name="$gallery_name_input"
fi

read -p "Enter image file extension(s) to look for or leave blank for all images (e.g., 'JPG' or 'png, jpg, gif, jpeg'): " file_extensions
if [ -z "$file_extensions" ]; then
    file_extensions="png, jpg, gif, jpeg, tif, tiff"
fi
file_extensions=$(echo "$file_extensions" | tr '[:upper:]' '[:lower:]' | sed 's/ //g')
regex=".*\.($(echo "$file_extensions" | sed 's/,/|/g'))$"
files=$(find . -maxdepth 1 -type f | grep -Ei "$regex")

output_dir="$gallery_name"
mkdir -p "$output_dir"

# Create index.gmi and add header
index_file="$output_dir/index.gmi"
echo -e "# Gallery: $gallery_name\n\n" > "$index_file"

# Iterate through each file matching the specified types
count=1
for file in $files; do
    echo "Processing $file"
    filename=$(basename "$file")
    if [ -z "$gallery_name_input" ]; then
        output_filename="${filename%.*}.gmi"
    else
        output_filename="${gallery_name}-${count}.gmi"
    fi
    
    # Generate individual .gmi files
    { printf '```\r\n'; chafa $chafa_settings "$file"; printf '\r\n```'; } > "$output_dir/$output_filename"
    
    # Generate gallery entry
    encoded_gmi_filename=$(printf '%s' "$output_filename" | LC_CTYPE=C LANG=C sed -E 's/([^a-zA-Z0-9._~-])/\\%\1/g')
    filesize=$(du -k "$file" | awk '{print $1}')
    echo "=> $encoded_gmi_filename 🖻 $encoded_gmi_filename ($filesize kbytes)" >> "$index_file"
    
    ((count++))
done

# Add file count and creation date to index.gmi
echo -e "\n$(($count - 1)) files; created on $current_date." >> "$index_file"