#!/bin/sh

case "$1" in
  # First check common extensions
  *.png|*.jpg|*.bmp|*.jpeg|*.gif|*.xpm|*.svg) mediainfo "$1" || exiftool "$1" || identify "$1" ;;
  *.wav|*.mp3|*.flac|*.m4a|*.ape|*.ac3|*.og[agx]|*.spx|*.dsf|*.opus|*.dff|*.wma|*.wvc?) mediainfo "$1" || exiftool "$1" ;;
  *.avi|*.mp4|*.wmv|*.dat|*.3gp|*.vob|*.ogv|*.mkv|*.mpe?g|*.fl[icv]|*.m2v|*.webm|*.m?ts|*.r[am]|*.qt|*.divx|*.as[fx]|*.m4v|*.mov) mediainfo "$1" || exiftool "$1" || fprobe -pretty "$1" 2>&1 ;;
  *.pdf) mutool draw -F txt -i -- "$1" 1-10 || pdftotext -l 10 -nopgbrk -q -- "$1" - || exiftool "$1" ;;
  *.ps) pstotext "$1" || ps2ascii "$1" ;;
  *.epub|*.fb2) pandoc -s -t markdown -- "$1" ;;
  *.djvu) djvutxt "$1" || exiftool "$1" ;;
  # *.ttf|*.otf) otfinfo --info "$1" ;;
  *.html|*.xhtml|*.htm) pandoc -s -t markdown -- "$1" || lynx -dump -- "$1" ;;
  *.mkd|*.md|*.markdown) glow -s dark "$1" || mdcat "$1" ;;
  *.ipynb) notedown --from notebook "$1" --to markdown | pandoc -f markdown -t plain ;;
  *.torrent) dumptorrent -v "$1" || transmission-show -- "$1" ;;
  *.zip|*.war|*.ear|*.oxt|*.tar|*.tgz|*.tar.gz|*.tbz2|*.tar.bz2|*.tar.txz|*.txz|*.rar|*.7z|*.ace|*.rpm|*.deb|*.xbps|*.Z|*.lzo|*.lzma|*.lha|*.cpio|*.jar|*.lz|*.lzh)
    atool -l -q "$1" | tail -n +3 | awk -F'   ' '{print $NF}' ;;
  *.iso) isoinfo -l -i "$1" ;;
  *.doc) catdoc -- "$1" ;;
  *.docx) pandoc -s -t markdown -- "$1" ;;
  *.odt|*.ott|*.s[xt]w|*.sxc) pandoc -s -t markdown -- "$1" || odt2txt "$1" ;;
  *.xls) xls2csv -- "$1" ;;
  *.xlsx) xlsx2csv -- "$1" ;;
  *.ods|*.odp|*.sxw) pandoc -s -t markdown -- "$1" ;;
  *.json) jq --color-output . "$1" || python -m json.tool -- "$1" ;;
  # Then fallback to mimetypes
  *)
    mimetype=$(file --dereference --brief --mime-type -- "$1")
    case "$mimetype" in
      inode/directory)
        # Don't preview the inode ../
        if [ -z "${1##*/..*}" ]
        then
          echo ""
        else
          echo "\0"
          exa -1a --color always --icons "$1"
        fi ;;
      application/zip | application/x-tar | application/x-rar | application/x-7z-compressed | application/x-xz | application/x-bzip2 | application/x-gzip)
        atool -l -q "$1" | tail -n +3 | awk -F'   ' '{print $NF}' ;;
      image/vnd.djvu)
        djvutxt "$1" || exiftool "$1" ;;
      image/*)
        mediainfo "$1" || exiftool "$1" || identify "$1" ;;
      video/*)
        mediainfo "$1" || exiftool "$1" || fprobe -pretty "$1" 2>&1 ;;
      text/* | */xml)
        # vifm doesn't support 24bit color for now
        env -uCOLORTERM bat --style=plain --color=always "$1" ;;
      *)
        echo '----- File Type Classification -----' && file --dereference --brief -- "$1" ;;
    esac ;;
esac
