#!/bin/sh -e
# vim: ft=sh:sw=2:ts=2:sts=2:fdm=marker:fdl=0:noml:
#
# print/preview a file to stdout, with graceful binary file handling, syntax highlighting and
# automatic paging.

file="$1"
encoding=$(file --brief --dereference --mime-encoding -- "${file}")

if [ "${encoding}" = "binary" ]; then
  mime=$(file --brief --dereference --mime-type -- "${file}")
  printf '\033[7m'
  echo "${mime}"
  printf '\033[0m\n'

  case "${mime}" in
    application/x-tar | application/gzip | application/x-bzip2 | application/x-xz)
      tar -tf "${file}"
      ;;
    application/zip | application/java-archive)
      zip -sf "${file}"
      ;;
    application/x-rar)
      rar l -- "${file}"
      ;;
    application/x-7z-compressed)
      7z l -- "${file}"
      ;;
    *)
      exiftool -veryShort -Title -Creator -Artist -Album \
        -Duration -ImageSize -PageCount -- "${file}"
      ;;
  esac
else
  mime=$(file --mime-type --brief -- "${file}")
  case "${mime}" in
    text/x-tex)
      latexrun "${file}"
      ;;
    text/plain)
      bat "${file}"
      ;;
    *)
      bat --plain --theme base16 --color always -- "$@"
      ;;
  esac
fi
