#!/usr/bin/env sh

input="${*:-}"
input_file_with_linenum=$(printf '%b' "${input}" | cut -d ':' -f 1)
command_history=$(printf '%b' "${input}" | tr -s ' ' | cut -d ' ' -f 2-)
mime=$(file -L -i -- "${input}" | awk -F": " '{ print $2 }')

# printf '%b' "${input}" is a binary file
# shellcheck disable=SC2312
if [ -e "${input}" ]; then
  if [ -d "${input}" ]; then
    ls -1 -- "${input}"
  elif file -i -- "${input}" | grep -q "binary"; then
    printf "\033[7m"
    echo "${mime}"
    printf "\033[0m\n"
  fi

elif [ -e "${input_file_with_linenum}" ] \
  && expr "X${input}" : 'X.*:[[:digit:]]*:.*' >/dev/null; then
  # grep
  n=$(printf '%b' "${input}" | cut -d : -f 2)
  (
    bat --color=always --style=grid,header "${input_file_with_linenum}" \
      || tail +"${n}" "${input_file_with_linenum}"
  ) 2>/dev/null | tail +"${n}"

elif [ -e "$(printf '%b' "${input}" | cut -d " " -f 2 2>/dev/null)" ]; then
  # file
  f=$(printf '%b' "${input}" | cut -d " " -f 2)
  (bat --color=always --style=grid,header "${f}") 2>/dev/null

elif command -v "$(printf '%b' "${command_history}" | cut -d ' ' -f 1)" >/dev/null 2>&1; then
  # history
  (
    printf '%b' "${command_history}" \
      | bat --color=always --wrap never --language=sh --style=plain \
      || printf '%b' "${command_history}"
  ) 2>/dev/null

else
  (
    printf '%b' "${input}" | bat --color=always --wrap never --style=plain \
      || printf '%b' "${input}"
  ) 2>/dev/null
fi
