#!/usr/bin/env bash
# pad-photo.sh: fit a whole photo inside a canvas and fill the rest with a colour (no crop).
# Usage: pad-photo.sh input.jpg output.png WIDTH HEIGHT [COLOR]
# COLOR is white by default; use a name (black) or hex (0xF2E8D5).
# Needs ffmpeg. The output format follows the output file extension (.png is lossless, .jpg is not).
set -euo pipefail

in=${1:-}; out=${2:-}; w=${3:-}; h=${4:-}; color=${5:-white}
w=${w//$'\r'/}; h=${h//$'\r'/}; color=${color//$'\r'/}

if [ "$#" -lt 4 ]; then echo "usage: $0 input output WIDTH HEIGHT [COLOR]" >&2; exit 2; fi
command -v ffmpeg >/dev/null || { echo "ffmpeg not found" >&2; exit 2; }
[ -f "$in" ] || { echo "input not found: $in" >&2; exit 2; }
[ -s "$in" ] || { echo "input is empty: $in" >&2; exit 2; }
case "$w$h" in ''|*[!0-9]*) echo "WIDTH and HEIGHT must be whole numbers" >&2; exit 2;; esac
[ "$w" -gt 0 ] && [ "$h" -gt 0 ] || { echo "WIDTH and HEIGHT must be above 0" >&2; exit 2; }

if ! ffmpeg -nostdin -v error -y -i "$in" \
  -vf "scale=${w}:${h}:force_original_aspect_ratio=decrease,pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2:color=${color}" \
  -frames:v 1 "$out" 2>/dev/null; then
  echo "could not read an image from $in, or could not write $out (check the file type and the colour)" >&2; exit 2
fi
echo "wrote $out (${w}x${h}, whole photo kept, bars: ${color})"
