#!/usr/bin/env bash
set -euo pipefail

export XDG_RUNTIME_DIR=/run/user/$(id -u)
export WAYLAND_DISPLAY=wayland-1
WIN=${WIN:=0}

if [ "$WIN" == "1" ]; then
  export TERM_PROGRAM=WezTerm
  export COLORTERM=truecolor
fi

# Frames per second. Start low; rendering images in a terminal is expensive.
fps="${FPS:-2}"
delay="$(awk -v fps="$fps" 'BEGIN {
    if (fps <= 0) exit 1
    printf "%.4f", 1 / fps
}')"

cleanup() {
    # Show cursor and leave the alternate-screen buffer.
    printf '\033[?25h\033[?1049l'
    if [ "$WIN" = "1" ]; then
      clear
    fi
}

trap cleanup EXIT INT TERM

# Enter alternate screen, clear it, move home, and hide the cursor.
if [ "$WIN" != "1" ]; then
  printf '\033[?1049h\033[2J\033[H\033[?25l'
fi

while true; do
    # Move to the top-left before replacing the frame.
    if [ "$WIN" != "1" ]; then
      printf '\033[H'
    fi

    # Extra command-line arguments are passed directly to grim.
    grim "$@" - |
        viu --absolute-offset -x 0 -y 0 -

    sleep "$delay"
done
