#!/bin/sh
#
# fzf-prvw - for use with fzf: `fzf --preview='fzf-prvw {}'`
# dependencies: bat | chafa | exiftool | ffmpeg | lynx | odt2txt | poppler
# optional: atool | media-info | w3m

set -eu

case "${TERM-}" in
  xterm-kitty)
    FZF_PREVIEW_IMAGE_HANDLER="kitty"
    ;;
  # xterm-256color)
  #   if command -v wezterm >/dev/null 2>&1; then
  #     FZF_PREVIEW_IMAGE_HANDLER="wezterm"
  #   else
  #     FZF_PREVIEW_IMAGE_HANDLER=
  #   fi
  #   ;;
  *)
    FZF_PREVIEW_IMAGE_HANDLER=
    ;;
esac

file="$1"
extension="${file##*.}"
extension=$(printf '%s' "${extension}" | tr '[:upper:]' '[:lower:]')
# extension="${ext}"

# unique non-existent cache file path
# utilised to cache the thumbnail of the file when needed
# test -d "${HOME%/}/.cache/fzf" || mkdir -p "${HOME%/}/.cache/fzf"
# shellcheck disable=SC2312
# cache_file="${HOME%/}/.cache/fzf/thumbnail.$(printf '%s' "$(readlink -f "$1")" | sha256sum | awk '{ print $1 }')"

# functions to handle specific type of files
handle_text() {
  case "${extension}" in
    md)
      (
        bat --language=markdown -- "${file}" || cat -- "${file}"
      ) 2>/dev/null
      ;;
    htm | html)
      lynx -force_html -dump "${file}"
      ;;
    *)
      bat --plain --color=always -- "${file}"
      ;;
  esac
}

# ishtml () {
#   # [ "$1" = "-" ] && arg1=-stdin || arg1="$1"
#   htmlopt=--unicode-snob
#   has_cmd html2text && html2text -utf8 </dev/null 2>/dev/null && htmlopt=-utf8
#   # 3 lines following can easily be reshuffled according to the preferred tool
#   has_cmd elinks && nodash "elinks -dump -force-html" "$1" && return ||
#   has_cmd w3m && handle_w3m "$1" && return ||
#   has_cmd lynx && lynx -force_html -dump "$arg1" && return ||
#   # different versions of html2text existing, force unicode
#   [[ "$1" = https://* ]] && return ||
#   has_cmd html2text && nodash html2text "$htmlopt" "$1"
# }

resolve_symlink() {
  TARGET="$(readlink "${file}")"
  printf '%b\n' "Symbolic link to: \e[34m${TARGET}\e[0m"
}

# shellcheck disable=SC2120
handle_image() {
  # image handling can be done in multiple ways

  image=${1:-${file}}
  columns=$(stty </dev/tty size 2>/dev/null | awk '{ print $2 }' || echo "80")
  cols=$((columns / 2 - 1))
  FZF_PREVIEW_COLUMNS="${cols}"
  FZF_PREVIEW_LINES="${FZF_PREVIEW_LINES:-$((cols / 2))}"

  if [ -n "${FZF_PREVIEW_IMAGE_HANDLER-}" ]; then
    case "${FZF_PREVIEW_IMAGE_HANDLER}" in
      kitty)
        # shellcheck disable=SC2016,SC3003
        kitten icat --clear --transfer-mode=memory \
          --unicode-placeholder --stdin=no \
          --place="${FZF_PREVIEW_COLUMNS}x$((FZF_PREVIEW_LINES - 1))@0x0" \
          -- "${image}" | sed '$d' | sed $'$s/$/\e[m/'

        # image related data appended after the image
        exiftool "${image}" || mediainfo "${image}"
        ;;
      *)
        chafa --clear --symbols all-braille-extra --colors full --animate off \
          --size "${FZF_PREVIEW_COLUMNS}x${FZF_PREVIEW_LINES}" -- "${image}"

        exiftool "${image}" || mediainfo "${image}"
        ;;
    esac
  else
    (
      chafa --symbols all-braille-extra --colors full --animate off \
        --size "${FZF_PREVIEW_COLUMNS}x${FZF_PREVIEW_LINES}" \
        --clear -- "${image}" \
        || exiftool "${image}"
    ) 2>/dev/null
  fi

}

mime=$(file -L -i -- "${file}" | awk -F": " '{ print $2 }')
handle_mime() {
  # handles file/folder type via mimetype
  case "${mime}" in
    text/troff | text/x-c)
      (
        bat --color=always --language=groff -- "${file}" || cat -- "${file}"
      ) 2>/dev/null
      ;;
    text/*)
      handle_text
      ;;
    message/*)
      reader --image-mode none -- "${file}" \
        || reader --eml --image-mode none -- "${file}"
      ;;
    inode/directory)
      (
        eza -T -L 2 "${file}" \
          || tree -L 1 -ah --charset=X -I ".git" "${file}" \
          || find "${file}" -maxdepth 1 -path '*/.git' -prune -o -print \
          | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
      ) 2>/dev/null
      ;;
    inode/symlink)
      resolve_symlink
      ;;
    application/json)
      bat -- "${file}" | jq --color-output . 2>/dev/null
      ;;
    application/x-executable | application/x-pie-executable | application/x-sharedlib)
      (
        bininfo -- "${file}" \
          || file -L -i "${file}" \
          || hexyl --length=8KiB -- "${file}" \
          || xx -a -g 8 -- "${file}" \
          || exiftool -- "${file}"
      ) 2>/dev/null
      # readelf --wide --demangle=auto --all "${file}"
      ;;
    application/x-x509-ca-cert)
      openssl x509 -text -noout -in "${file}"
      ;;
    application/pdf)
      pdftotext -layout -nopgbrk -q -- "${file}" /dev/stdout
      # pdftoppm -jpeg -f 1 -singlefile "${file}" "${cache_file}"
      # handle_image "${cache_file}.jpg"
      ;;
    image/*)
      handle_image
      ;;
    video/*)
      ffprobe -hide_banner -- "${file}"
      # ffmpegthumbnailer -i "${file}" -o "${cache_file}.jpg" -s 1200
      # handle_image "${cache_file}.jpg"
      ;;
    *)
      handle_extension
      ;;
  esac
}

handle_extension() {
  case "${extension}" in
    a | ace | alz | arc | arj | bz | bz2 | cab | cpio | deb | gz | jar | lha | \
      lz | lzh | lzma | lzo | rpm | rz | t7z | tar | tbz | tbz2 | tgz | tlz | \
      txz | tZ | tzo | war | xpi | xz | Z | zip | rar)
      if command -v bsdtar >/dev/null 2>&1; then
        bsdtar tf "${file}"
      elif command -v atool >/dev/null 2>&1; then
        atool --list "${file}" && exit 0
        exit 1
      else
        less -- "${file}"
      fi
      ;;
    7z)
      7z l -p -- "${file}" && exit 0
      exit 1
      ;;
    o)
      nm "${file}"
      ;;
    iso)
      if command -v bsdtar >/dev/null; then
        bsdtar tf "${file}"
      else
        iso-info --no-header -l "${file}"
      fi
      ;;
    odt | ods | odp | sxw)
      if command -v pandoc >/dev/null; then
        pandoc -f odt -t plain "${file}"
      else
        odt2txt "${file}"
      fi
      ;;
    doc)
      catdoc "${file}"
      ;;
    docx)
      docx2txt "${file}" -
      ;;
    xls | xlsx)
      if command -v xlsx2csv >/dev/null; then
        xlsx2csv "${file}"
      elif command -v qsv >/dev/null; then
        qsv excel --flexible "${file}"
      else
        ssconvert --export-type=Gnumeric_stf:stf_csv "${file}" "fd://1" \
          | bat --language=csv
      fi
      ;;
    wav | mp3 | flac | m4a | wma | ape | ac3 | og[agx] | spx | opus | as[fx] | mka)
      exiftool "${file}"
      ;;
    *)
      (file -L "${file}" || exiftool "${file}") 2>/dev/null
      ;;
  esac
}

handle_mime
