#!/bin/sh

[ -d "$HOME/.cache/vifm" ] || mkdir -p ~/.cache/vifm

WIDTH="$2"
HEIGHT="$3"
TMP="$HOME/.cache/vifm/thumbnail.$(stat --printf '%n\0%i\0%F\0%s\0%W\0%Y' -- "$(readlink -f "$1")" | sha256sum | awk '{print $1}')"

_show_sixel() {
    # Stolen from vifm/vifm#419
    pw=$(($2*8))
    ph=$(($3*21))

    w=$(exiftool -m -p '$ImageWidth' "$1")
    h=$(exiftool -m -p '$ImageHeight' "$1")

    height=auto
    width=auto
    if [ $pw -lt $w ] && [ $ph -lt $h ]
    then
        newh=$(echo "($h*$pw)/$w" | bc)
        # neww=$(echo "($w*$ph)/$h" | bc)

        if [ $newh -le $ph ]; then
            width=$pw
        else
            height=$ph
        fi
    elif [ $pw -lt $w ]
    then
        width=$pw
    elif [ $ph -lt $h ]
    then
        height=$ph
    fi

    # debugging stuff
    # echo pw=$pw ph=$ph
    # echo w=$w h=$h
    # echo neww=$neww newh=$newh
    # exec echo width=$width height=$height

    # account for GNU screen
    if [ -n "$STY" ]
    then
        popt=-P
    fi

    exec img2sixel $popt --width=$width --height=$height "$1" # require libsixel
    # exec montage "$1" -geometry "${pw}x${ph}" sixel:- # require ImageMagick
}

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

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

case "$1" in
  # First check common extensions
  *.png|*.jpg|*.bmp|*.jpeg|*.gif|*.xpm) _show_sixel "$1" ${WIDTH} ${HEIGHT} ;;
  *.avi|*.mp4|*.wmv|*.dat|*.3gp|*.vob|*.ogv|*.mkv|*.mpe?g|*.fl[icv]|*.m2v|*.webm|*.m?ts|*.r[am]|*.qt|*.divx|*.as[fx]|*.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/font*|application/*opentype|font/*)
        [ ! -f "${TMP}.jpg" ] && genfontimage "$1" "${TMP}.jpg"
        _show_sixel "${TMP}.jpg" ${WIDTH} ${HEIGHT} ;;
      video/*)
        _preview_video "$1" ;;
      *)
        exit 1 ;;
    esac ;;
esac
