#!/bin/sh -e
#
# cjson - [c]at the given files as prettified [j]son
# dependencies: jq | less
# optional: bat

page() {
  if command -v bat >/dev/null; then
    bat --language=json --style numbers
  else
    python -m json.tool | less -XRF
  fi
}

# jq if file is valid json, otherwise show parseable lines with bat
{
  jq --unbuffered '.' "$@" \
    ||
    # add echo in case file is missing newline at the end
    {
      for arg; do
        echo "FILE: ${arg} ─────────────────────────────────────────────────────────────────────────────────────────"
        cat "${arg}"
      done
      echo
    } \
    | while read -r line; do
      line="${line%
}"
      if command expr length "${line}" \> 2 \& "${line}" : FILE = 0 >/dev/null 2>&1; then
        echo "${line%,}" | python3 -m json.tool --no-ensure-ascii --sort-keys
      else
        echo "${line}"
      fi
    done
} | page
