#!/usr/bin/env bash

input="$1"

# Skip: empty, non-image, icons, or too small.
if [[ ! -s "$input" ]]; then
  exit
fi

if [[ "$input" != *.jpg && "$input" != *.svg && "$input" != *.png ]]; then
  exit
fi

if [[ "$input" == usr/share/icons/* ]]; then
  exit
fi

input_size="$(stat -c '%s' "$input")"

if [[ "$input_size" -lt "$(( 4 * 1024 ))" ]]; then
  exit
fi

output=''

if [[ "$input" == *.png ]]; then
  output="$(mktemp --suffix=.png)"
  cp "$input" "$output"
  # Lossy, controlled: keep perceptual quality >= 80. Write to a separate
  # temp and only swap in on success, so a skip/failure never leaves a
  # half-written $output for optipng to read.
  pngquant_out="$(mktemp --suffix=.png)"
  if pngquant --quality=80-95 --skip-if-larger --strip --force --output "$pngquant_out" "$output" 2>/dev/null; then
    mv "$pngquant_out" "$output"
  else
    rm -f "$pngquant_out"
  fi
  # Lossless final squeeze.
  optipng -strip all -o3 "$output" 2>/dev/null
fi

if [[ "$input" == *.jpg ]]; then
  output="$(mktemp --suffix=.jpg)"
  cp "$input" "$output"
  jpegoptim --quiet --strip-all -m30 "$output" 2>/dev/null
fi

if [[ "$input" == *.svg ]]; then
  output="$(mktemp --suffix=.svg)"
  svgo --multipass --quiet -i "$input" -o "$output" 2>/dev/null
fi

if [[ ! -s "$output" ]]; then
  rm -f "$output"
  exit
fi

output_size="$(stat -c '%s' "$output")"

# Never enlarge.
if [[ "$input_size" -le "$output_size" ]]; then
  rm -f "$output"
  exit
fi

cat "$output" > "$input"

echo "  -> /$input $(numfmt --to=iec "$input_size")/$(numfmt --to=iec "$output_size")"

rm -f "$output"
