#!/usr/bin/env bash

# Folder with full-size wallpapers
WALLPAPER_DIR="$HOME/Pictures/Wallpapers"

# Folder to store thumbnails
THUMB_DIR="$HOME/.cache/wallpaper-thumbs"

if [ ! -d $THUMB_DIR ]; then
  mkdir -p $THUMB_DIR;
fi

shopt -s nullglob
files=( "$THUMB_DIR"/*.jpg "$THUMB_DIR"/*.jpeg "$THUMB_DIR"/*.png )
# printf '  %s\n' "${files[@]}"
# Make sure the thumb directory exists
mkdir -p "$THUMB_DIR"

# Max width/height of the thumbnails
MAX_DIM=300

num=0

remove_from_array() {
    local -n arr=$1
    local elem=$2
    local result=()

    # echo "=== Removing element: '$elem' ==="
    # echo "Original array has ${#arr[@]} elements"

    for item in "${arr[@]}"; do
        if [[ "$item" != "$elem" ]]; then
            result+=( "$item" )
        #     echo "Keeping: '$item'"
        # else
        #     echo "Removing: '$item'"
        fi
    done

    arr=( "${result[@]}" )
    # echo "New array has ${#arr[@]} elements"
    # echo "-----------------------------------"
}

# Process each image
for img in "$WALLPAPER_DIR"/*.{jpg,jpeg,png}; do
    # Skip if no files match
    [ -e "$img" ] || continue

    # Get just the filename
    fname=$(basename "$img")
    name="${fname%.*}"
    ext="${fname##*.}"

    # no magick file:
    temp_image_name="$THUMB_DIR/${name}_tmp.${ext}" 

    # Output path
    thumb="$THUMB_DIR/$fname"
    

    # If thumbnail already exists and is newer than the original, skip
    if [ -f "$thumb" ] && [ "$thumb" -nt "$img" ]; then
        remove_from_array files "$thumb"
        continue
    fi

    num+=1

    # Generate thumbnail using ImageMagick
    if [ -x "/usr/bin/magick" ]; then
        magick "$img" -resize "${MAX_DIM}x${MAX_DIM}" "$thumb"
        rm $temp_image_name
    else
        if [ -f "$temp_image_name" ] && [ "$temp_image_name" -nt "$img" ]; then
            continue
        fi
        cp $img $temp_image_name
    fi
    remove_from_array files "$thumb"
done

# echo ""

# printf '  %s\n' "${files[@]}"

for img in $files; do
    # echo "$img"
    rm $img
done

echo "$num Thumbnails generated in $THUMB_DIR"