#!/bin/sh
#
# hiless - have highlight read from STDIN if '-' is given as filename
# dependencies: hilight (optional) | bat
#
# setup:
#       setup - add to .bashrc:
#       LESSOPEN='|-highlight-less-wrapper "%s"'
#       export LESS=-FMRXis
#
# usage:
#       $ less file
#   OR
#       $ pipeline | less

warn() {
  printf '%s: %s\n' "$(basename "$0")" "$*" 1>&2
}

die() {
  warn "$@"
  exit 1
}

# argument checking
case "$#" in
  0)
    # allow `exec $0` for less setup
    # shellcheck disable=SC2312
    echo "LESSOPEN='|-$(readlink -f "$0") "'"%s"'\'
    exit 255
    ;;
  1)
    # only one argument is expected.
    # less will invoke multiple times given multiple files.
    file="$1"
    if [ "${file}" != - ] && [ ! -r "${file}" ]; then # less passes '-' for STDIN
      die "Cannot open ${file} for reading"
    fi
    ;;
  *)
    die "Expected only one argument"
    ;;
esac

# run highlight(1)
# highlight will read from STDIN when given a null filename
run_highlight() {
  if command -v highlight >/dev/null 2>&1; then
    highlight --force --out-format=truecolor --style=aiseered "$1"
  elif command -v bat >/dev/null 2>&1; then
    bat --color=always "$1"
  else
    cat "$1"
  fi
}

if [ "${file}" = - ]; then # run on stdin
  run_highlight ""
else
  run_highlight "${file}"
fi
