#!/bin/bash -e

if [ -z "$1" ]; then
    echo "Usage: $0 <path/to/flair/dir>"
    exit 1
fi

exit_code=0
flairs_checked=0

for img_file in "$1"/*; do
    if [[ ! "$img_file" =~ \.webp$ ]]; then
        echo "Not a WEBP: $img_file"
        exit_code=1
        continue
    fi

    dimensions=$(identify -format "%wx%h" "$img_file")

    width=$(echo "$dimensions" | cut -d 'x' -f 1)
    height=$(echo "$dimensions" | cut -d 'x' -f 2)

    if [ "$width" -ne "$height" ]; then
        echo "Not square: $img_file ($dimensions)"
        exit_code=1

        echo "Converting to square..."
        max_dimension=$((width > height ? width : height))
        convert "$img_file" -gravity center -background transparent -extent "${max_dimension}x${max_dimension}" "$img_file"
    fi

    if [ "$width" -lt 60 ] || [ "$width" -gt 100 ]; then
        echo "Not between 60-100px: $img_file ($dimensions)"
        exit_code=1

        echo "Resizing to 100px..."
        convert "$img_file" -resize 100x100 "$img_file"
    fi

    # animated WEBPs contain the string "ANMF" in the file
    if grep -q "ANMF" "$img_file"; then
        echo "Animated: $img_file"
        exit_code=1
    fi

    flairs_checked=$((flairs_checked + 1))
    if [ $((flairs_checked % 100)) -eq 0 ]; then
        echo "Checked $flairs_checked flair images so far..."
    fi
done

if [ "$exit_code" -eq 0 ]; then
    echo "✅ Images are OK"
fi

exit $exit_code
