#!/bin/sh -e
#
# readme - pager for README files with optional bat/glow/less/pandoc support

# tty size
COLUMNS="$(stty size </dev/tty | awk '{ print $2 }')"
COLUMNS="${COLUMNS:-80}"

if [ -n "$1" ] && [ -f "$1" ]; then
  file="$1"
elif [ -d "$1" ]; then
  dir="$1"
  cd -- "${dir}" && shift
  file=$(find . -maxdepth 1 -iname 'readme*' -type f | head -n 1)
elif [ "$#" -eq 0 ]; then
  file=$(find . -maxdepth 1 -iname 'readme*' -type f | head -n 1)
  test -n "${file}" \
    || file=$(
      find . -maxdepth 1 \( -iname 'changes*' -o -iname 'news*' \) -type f \
        | head -n 1
    )
fi

if [ -z "${file}" ]; then
  printf '%s\n' "${0##*/}: no README file found!" >&2
  exit 2
fi

filepath="$(readlink -f "${file}")"
footer="$(printf '%s' "${filepath}" | sed "s|^$HOME|~|")"
extension="${file##*.}"

case "${extension}" in
  [0-9]*) man "${filepath}" ;;
  *)
    if command -v bat >/dev/null 2>&1; then
      bat --language=markdown --style=header \
        --terminal-width=$((COLUMNS - 10)) "${file}"
    elif command -v pandoc >/dev/null 2>&1; then
      # markman
      pandoc --standalone --from markdown-smart --to man "${file}" \
        --metadata header="$(basename "${file}")" \
        --metadata footer="${footer}" \
        | MANPAGER="less -RF" man --local-file -
    elif command -v glow >/dev/null 2>&1; then
      glow --style ascii --width $((COLUMNS - 10)) --pager "${file}"
    else
      cat "${file}" | less -RF
    fi
    ;;
esac
