#!/bin/sh -e
#
# prvw - preview file to stdout, with binary file handling/syntax highl/paging

if [ "$#" -eq 0 ]; then
  printf '%s\n' "$(basename "$0") [file]" >&2
  exit 1
fi

file="$1"
extension="${file##*.}"
encoding=$(file -L -i -- "${file}" | cut -d '=' -f 2)
mime=$(file -L -i -- "${file}" | awk -F": " '{ print $2 }')

# todo(2025-12-18): .doc .xlsx
# mudoc - read .doc with mupdf
# mupdf =(antiword -a a4 -m 8859-1 "$@")
# mudoc - read .doc with mupdf
# mudoc() { mupdf =(antiword -a a4 -m 8859-1 "$@") }

if [ "${encoding}" = "binary" ]; then
  printf "\033[7m"
  echo "${mime}"
  printf "\033[0m\n"

  # shellcheck disable=SC2249
  case "${extension}" in
    zip) zip -sf "${file}" ;;
  esac

  case "${mime}" in
    application/x-bplist*)
      (
        command -p plutil -p -- "${file}" \
          || plistutil --compact --print -- "${file}"
      ) 2>/dev/null
      ;;
    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}"
      ;;
    application/octet-stream*)
      dex -p "${file}" | fold -w 80 -s
      ;;
    application/pdf*)
      pdftohtml "${file}" -i -f 1 -l 3 -stdout | reader -
      ;;
    *)
      (
        exiftool -veryShort -Title -Creator -Artist -Album -Duration \
          -ImageSize -PageCount -- "${file}" \
          || exiftool -- "${file}"
      ) 2>/dev/null
      ;;
  esac
else
  case "${mime}" in
    message/rfc822*)
      (
        reader --eml -- "${file}" \
          || bat --color=always --language=eml -- "${file}"
      ) 2>/dev/null
      ;;
    *)
      bat --color=always --plain --theme=ansi -- "$@"
      ;;
  esac
fi
