#!/bin/sh

# https://github.com/eylles/vifm-sixel-preview/pull/2
# https://github.com/vifm/vifm/issues/419#issuecomment-485918513

# require ImageMagick, chafa

thumbnail_dir="$HOME/.cache/vifm/thumbnails"

[ ! -d "${thumbnail_dir}" ] && mkdir -p "${thumbnail_dir}"

WIDTH="$2"
HEIGHT="$3"
TMP="${thumbnail_dir}/thumbnail.$(stat -c '%n%i%F%s%Y' -- "$(readlink -f "$1")" | sha256sum | awk '{print $1}')"

_show_graphics() {
  exec chafa --animate off -s "${WIDTH}x${HEIGHT}" "$1"
}

_preview_video() {
  [ ! -f "${TMP}.jpg" ] && ffmpegthumbnailer -i "$1" -o "${TMP}.jpg" -s 0
  _show_graphics "${TMP}.jpg"
}

_preview_image() {
  [ ! -f "${TMP}.jpg" ] && convert -- "$1"'[0]' "${TMP}.jpg"
  _show_graphics "${TMP}.jpg"
}

_preview_font() {
  [ ! -f "${TMP}.jpg" ] && ~/.local/libexec/genfontimage "$1" "${TMP}.jpg"
  _show_graphics "${TMP}.jpg"
}

case "$1" in
  # First check common extensions
  *.png|*.PNG|*.jpg|*.JPG|*.bmp|*.jpeg|*.gif|*.xpm|*.webp|*.WEBP) _show_graphics "$1" ;;
  *.avi|*.mp4|*.wmv|*.dat|*.3gp|*.vob|*.ogv|*.mkv|*.mpg|*.mpeg|*.fli|*.flc|*.flv|*.m2v|*.webm|*.mts|*.qt|*.divx|*.asf|*.asx|*.m4v|*.mov)
    _preview_video "$1" ;;
  # Then fallback to mimetypes
  *)
    mimetype=$(file --dereference --brief --mime-type -- "$1")
    case "$mimetype" in
      image/vnd.djvu*)
        djvutxt "$1" || exiftool "$1" ;;
      image/*)
        _preview_image "$1" ;;
      application/x-font*|font/*)
        _preview_font "$1" ;;
      video/*)
        _preview_video "$1" ;;
      *)
        exit 1 ;;
    esac ;;
esac
