#!/bin/bash
# Generate mobile (480px wide) variants of every webp in images/
# Output: images/mobile/*.webp
# Requires: cwebp, dwebp (both from libwebp — brew install webp)

set -e
cd "$(dirname "$0")/images"
mkdir -p mobile

count=0
skipped=0
for f in *.webp; do
  out="mobile/$f"

  # Skip if already exists and is newer than source
  if [ -f "$out" ] && [ "$out" -nt "$f" ]; then
    skipped=$((skipped + 1))
    continue
  fi

  # Get source width
  width=$(dwebp -quiet "$f" -o /tmp/_probe.png 2>/dev/null && sips -g pixelWidth /tmp/_probe.png 2>/dev/null | awk '/pixelWidth/ {print $2}')

  # Skip already-small images (<= 500px wide) — just copy
  if [ -n "$width" ] && [ "$width" -le 500 ]; then
    cp "$f" "$out"
    echo "  copy (already small $width px): $f"
  else
    # Decode -> resize -> re-encode at quality 75
    dwebp -quiet "$f" -o /tmp/_src.png
    sips --resampleWidth 480 /tmp/_src.png --out /tmp/_resized.png >/dev/null 2>&1
    cwebp -quiet -q 75 /tmp/_resized.png -o "$out"
    old_size=$(stat -f%z "$f")
    new_size=$(stat -f%z "$out")
    printf "  resized: %-45s %6d -> %6d bytes (%d%%)\n" "$f" "$old_size" "$new_size" $((new_size * 100 / old_size))
  fi
  count=$((count + 1))
done

rm -f /tmp/_probe.png /tmp/_src.png /tmp/_resized.png

echo ""
echo "Done. Processed: $count, skipped (up-to-date): $skipped"
echo "Total size:"
du -sh . mobile
