#!/bin/sh

case "$(uname -a)" in
    *Darwin*) UEBERZUG_TMP_DIR="$TMPDIR" ;;
    *) UEBERZUG_TMP_DIR="/tmp" ;;
esac

cleanup() {
    ueberzugpp cmd -s "$SOCKET" -a exit
}
trap cleanup HUP INT QUIT TERM EXIT

UB_PID_FILE="$UEBERZUG_TMP_DIR/.$(uuidgen)"
ueberzugpp layer --no-stdin --silent --use-escape-codes --pid-file "$UB_PID_FILE"
UB_PID=$(cat "$UB_PID_FILE")

export SOCKET="$UEBERZUG_TMP_DIR"/ueberzugpp-"$UB_PID".socket
export X=$(($(tput cols) / 2 + 1))
# --max-width $FZF_PREVIEW_COLUMNS --max-height $FZF_PREVIEW_LINES
# if FZF_PREVIEW_COLUMNS exists, use it, otherwise use tput cols
[ -z "$FZF_PREVIEW_COLUMNS" ] && max_width=$(($(tput cols) - 2)) || max_width=$FZF_PREVIEW_COLUMNS
[ -z "$FZF_PREVIEW_LINES" ] && max_height=$(($(tput lines) - 2)) || max_height=$FZF_PREVIEW_LINES

# run fzf with preview
fzf --reverse --preview="ueberzugpp cmd -s $SOCKET -i fzfpreview -a add -x $X -y 1 --max-width $max_width --max-height $max_height -f {}"

ueberzugpp cmd -s "$SOCKET" -a exit
