#!/usr/bin/env sh
set -eu

FPS=${FPS:-16}
SCALE=${SCALE:-1}
CRF=${CRF:-21}
NAME=${1:-capture}
DISPLAY=${DISPLAY:-:0.0}
SLOP_OPTS=${SLOP_OPTS:-}

need() {
  command -v "$1" >/dev/null 2>&1 || {
    printf "fatal: %s not found\n" "$1"; exit 1;
  };
}

need slop
need ffmpeg

# Pick region/window: "x y w h"
set -- $(slop $SLOP_OPTS -f '%x %y %w %h') || { printf "aborted\n"; exit 1; }
x=$1 y=$2 w=$3 h=$4

VF="crop=iw-2:ih-2:1:1,fps=${FPS},scale=trunc(iw*${SCALE}/2)*2:trunc(ih*${SCALE}/2)*2"
ts=$(date +"%Y%m%d-%H%M%S")
out="${NAME}-${ts}.webm"

printf "recording… to %s (Ctrl-C)\n" "$out"

# Run ffmpeg in the foreground so it handles Ctrl-C itself and finalizes cleanly
exec ffmpeg -v warning \
  -video_size "${w}x${h}" \
  -framerate "${FPS}" \
  -f x11grab -i "${DISPLAY}+${x},${y}" \
  -vf "${VF}" \
  -c:v libvpx-vp9 -crf "${CRF}" -b:v 0 \
  -row-mt 1 -tile-columns 2 -tile-rows 1 \
  -pix_fmt yuv420p \
  "${out}"

# TIP: convert FILE.gif -strip -coalesce -layers Optimize OPTIMIZED.gif
