#!/usr/bin/env bash
# Shrink a picture to at most N bytes as a JPEG with ffmpeg: best quality at full size first, then smaller pictures.
# Usage: bash to-kb.sh <input image> <limit in bytes> <output.jpg>
# Needs ffmpeg and ffprobe. Draft setting, not a platform figure: it never goes below ffmpeg -q:v 12.
set -euo pipefail
in=${1:-}; limit=${2:-}; out=${3:-}
if [ -z "$in" ] || [ -z "$limit" ] || [ -z "$out" ]; then echo "to-kb: usage: bash to-kb.sh <input image> <limit in bytes> <output.jpg>" >&2; exit 2; fi
[ -f "$in" ] || { echo "to-kb: file not found: $in" >&2; exit 1; }
[ -s "$in" ] || { echo "to-kb: file is empty: $in" >&2; exit 1; }
case "$limit" in ""|*[!0-9]*|0) echo "to-kb: the limit must be a whole number of bytes, for example 102400" >&2; exit 2;; esac
w=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=p=0 -- "$in" 2>/dev/null | head -n 1 || true)
case "$w" in ""|*[!0-9]*|0) echo "to-kb: ffprobe could not read a picture from: $in" >&2; exit 1;; esac
dir=$(mktemp -d); trap 'rm -rf "$dir"' EXIT
encode() { ffmpeg -v error -y -i "$in" -vf "scale=$1:-2:flags=lanczos" -q:v "$2" -frames:v 1 -update 1 "$3"; wc -c < "$3" | tr -d " "; }
for pct in 100 90 80 70 60 50 40 30 20 10; do
  nw=$(( w * pct / 100 / 2 * 2 ))
  [ "$nw" -ge 16 ] || break
  bytes=$(encode "$nw" 12 "$dir/floor.jpg")
  [ "$bytes" -le "$limit" ] || continue
  best=12; cp "$dir/floor.jpg" "$dir/best.jpg"
  for q in 2 3 4 5 6 8 10; do
    bytes=$(encode "$nw" "$q" "$dir/try.jpg")
    if [ "$bytes" -le "$limit" ]; then best=$q; cp "$dir/try.jpg" "$dir/best.jpg"; break; fi
  done
  cp "$dir/best.jpg" "$out"
  echo "to-kb: ok: $(wc -c < "$out" | tr -d " ") bytes (limit $limit), width $nw px ($pct% of $w), ffmpeg -q:v $best -> $out"
  exit 0
done
echo "to-kb: could not reach $limit bytes with -q:v 12 or better and a width of at least 16 px" >&2
exit 3
