#!/bin/sh -e
#
# ---
# source: https://github.com/Ryooooooga/dotfiles

if [ "$#" -eq 0 ]; then
  printf '%s\n' "Usage: ${0##*/} [file | directory]"
  exit 1
fi

if [ -d "$1" ]; then
  if command -v eza >/dev/null 2>&1; then
    eza --tree --level=3 --all --git-ignore --ignore-glob=".git" --icons \
      --color=always -- "$1"
  elif command -v tree >/dev/null 2>&1; then
    tree -FC --charset=ascii -I '.git' -- "$1"
  else
    find -- "$1" -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
  fi
else
  mime=$(file -L -i -- "$1" | awk -F": " '{ print $2 }')
  case "${mime}" in
    application/x-bplist*)
      (
        command -p -- plutil -p -- "$1" \
          || plistutil --compact --print -- "$1"
      ) 2>/dev/null
      ;;
    application/pdf*)
      (
        pdftotext -f 1 -l 1 -layout -q -- "$1" /dev/stdout | fold -w 80 -s \
          || pdftohtml "$1" -i -f 1 -l 3 -stdout >/tmp/pdfpage.html
        lynx -force_html -width=80 /tmp/pdfpage.html -dump
        rm /tmp/pdfpage.html
      ) 2>/dev/null
      ;;
    video/*)
      (
        exiftool -- "$1" \
          || exif -- "$1"
      ) 2>/dev/null
      ;;
    image/*)
      (
        chafa --clear --symbols all-braille-extra --colors full \
          --animate off --scale 0.2 -- "$1" || exiftool -- "$1"
      ) 2>/dev/null
      ;;
    message/rfc822*)
      (
        reader --eml -- "$1" \
          || bat --color=always --language=eml -- "$1"
      ) 2>/dev/null
      ;;
    text/x-*)
      (
        highlight --out-format=ansi --line-numbers "$1" \
          || bat --color=always "$1" \
          || cat "$1"
      ) 2>/dev/null | head -500
      ;;
    application/x-mach-binary*)
      (
        bininfo "$1" \
          || file -L -i -- "$1" \
          || hexyl --length=8KiB -- "$1" \
          || xx -a -g 8 -- "$1" \
          || exiftool -- "$1"
      ) 2>/dev/null
      ;;
    application/zip*)
      (
        zip -sf "$1" || file -L -i -- "$1"
      ) 2>/dev/null
      ;;
    *)
      (
        bat --line-range=":200" --color=always -- "$1" \
          || head -n 200 -- "$1"
      ) 2>/dev/null
      ;;
  esac
fi
