#!/usr/bin/env sh
#
# p - [b]rowse - overview of given files or current directory
# dependencies: checkaccess | hi
# optional: timg | neovim (compressed files) | pdftoppm
# optional: mtn (video files) | audiowaveform | imagemagick
#
# args: files to inspect, any arg starting with dash is passed on to bat
#
# supports:
# - listing directories
# - listing contents of any compressed file with neovim
# - visual files are displayed with timg
#   video thumbnails via mtn, pdf pages from pdftoppm
# - text files are displayed through bat
# - usually automatically requests elevation through sudo when needed

# shellcheck disable=SC2249,SC2312

# set -o pipefail

inspect=false

if test "${#1}" -lt 4; then
  opts='irtxh'
  while getopts "${opts}" OPTION; do
    case "${OPTION}" in
      i) inspect=true ;;
      r) readme=true ;;
      t) tree=true ;;
      x)
        export PS4='+\#> '
        set -e
        set -o xtrace
        ;;
      h | \?)
        printf '%s\n' "Usage: $(basename "$0") [-${opts}] <paths...>"
        exit 2
        ;;
      --)
        break
        ;;
    esac
  done
  shift "$((OPTIND - 1))"
fi

checkperm() {
  checkaccess -r "$@" || elevate="sudo"
  mime="$(test -n "${shifted:-}" \
    || ${elevate} file --dereference --mime-type -- "$@")"
}

fileinfo() {
  for arg; do
    case "${arg}" in
      -*) continue ;;
    esac
    header=$(${elevate} file --exclude elf -E "${arg}")
    printf '\e[44;30m%b\e[0m' "${header}"

    stat=$(command -v gstat 2>/dev/null || echo stat)
    size=$(${stat} --format %s "${arg}")

    # print media infos over file infos when <2G
    if ! {
      test "${size}" -lt 2000000000 \
        && ${elevate} ffprobe -hide_banner "${arg}" 2>&1 \
        | grep -E "bitrate: .{3,5} " | sed 's/, start:[^,]\+,/,/'
    } || ${inspect}; then
      # shellcheck disable=SC2030
      ${elevate} "${stat}" --format "%U:%G %A %s $(
        size="$(${elevate} unzip -l "${arg}" 2>/dev/null | tail -1)" \
          && echo "(uncompressed $(echo "${size}" | cut -d' ' -f1 \
            | numfmt --to=iec-i --suffix=B))"
      ) - birth %.10w mod %.10y" "${arg}" \
        | numfmt --field=3 --to=iec-i --padding=6 --suffix=B
    fi
  done
  # check if SSH key (<10KB then read)
  # shellcheck disable=SC2031
  if test "${size:-99999}" -lt 10000; then
    ${elevate} ssh-keygen -l -f "${arg}" 2>/dev/null || true
  fi
}

prefix="${TMPDIR:-/tmp}/b-${PPID}"
mkdir -p "${prefix}"
cleanup() {
  rm -rf "${prefix}" 2>/dev/null
  pkill -P $$ 2>/dev/null
}
trap cleanup INT TERM EXIT
# mkfifo "${prefix}"
# trap 'rm -rf ${prefix}' EXIT
# trap 'rm -rf ${prefix}; exit' 0

cols="$(stty </dev/tty size 2>/dev/null | awk '{ print $2 }' || echo "80")"
lines="$(stty </dev/tty size 2>/dev/null | awk '{ print $1 }' || echo "24")"

# declare -a timg timga bat batplain ls
# timg="" timga="" bat="" batplain="" ls=""
# readonly timg timga bat batplain ls
for arg; do
  test -z "${noflags}" && case "${arg}" in
    --)
      noflags=true
      continue
      ;;
    -*)
      flags=""
      flags="${flags} ${arg}"
      continue
      ;;
  esac
  checkperm "${arg}"
  if ! ${elevate} test -e "${arg}"; then
    if test -h "${arg}"; then
      fileinfo "${arg}"
    else
      echo "File not found: '${arg}'" 1>&2
    fi
    continue
  fi
  # amount of items to display per line in a grid for two lines max
  # grid=$(expr $(cols) / \( 25 - \( $# / 2 \) \& $# \< 30 \| 5 \))
  grid=$((cols / (25 - ($# / 2) & $# < 30 | 5)))
  tmpfile="${prefix}/$(basename -- "${arg}")_$(dd "if=${arg}" bs=1M count=16 2>/dev/null | md5sum | cut -d' ' -f1 || true)"
  mkdir -p "${prefix}"
  case "${mime}" in
    *\ application/pdf)
      # grid=$(expr $(cols) \* $# / $(lines))
      # grid=$(expr 3 \& $grid \< 3 \| $grid)
      grid=$((cols * $# / lines))
      grid=$((3 & grid < 3 | grid))
      limit=${grid}
      if ! test -f "${tmpfile}-1.ppm"; then
        echo Converting "${arg}"
        pdftoppm -forcenum -r 70 "${arg}" "${tmpfile}" -l "${limit}"
      fi
      find "${prefix}" -path "${tmpfile}*.ppm" | sort | head -"${limit}" \
        | xe timg -W --grid="${grid}"
      # | xargs -d'\n' timg -W --grid="${grid}"
      ;;
    *\ application/*document* | *.xlsx:\ *)
      # see: https://ask.libreoffice.org/t/convert-to-command-line-parameter/840/4
      (
        command -v xlsx2csv 2>/dev/null \
          && xlsx2csv "${arg}"
      ) 2>/dev/null \
        || (
          command -v qsv 2>/dev/null && excel --flexible 2>/dev/null \
            || echo Converting "${arg}" \
              soffice --headless --convert-to png --outdir "${prefix}" "${arg}" \
              timg="${timg}${tmpfile%.*}.png" >/dev/null
        )
      ;;
    *\ application/x-bplist)
      (
        plutil -p -- "${arg}" \
          || plistutil --compact --print -- "${arg}"
      ) 2>/dev/null
      ;;
    *\ message/rfc822)
      (
        command -v reader >/dev/null \
          && reader --eml -- "${arg}"
      ) \
        || bat="${bat}${arg}"
      ;;
    */x-xcf*)
      echo Converting "${arg}"
      convert -flatten "${arg}" png:"${tmpfile}"
      timg="${timg}${tmpfile}"
      ;;
    # TODO .raw .img
    */x-iso* | */x-qemu-disk*)
      bsdtar tf "${arg}" || fdisk -l "${arg}"
      ;;
    *\ application/vnd.debian.binary-package)
      dpkg --contents -- "${arg}"
      ;;
    *\ video/*)
      # TODO sometimes duration mismatch for short videos
      suffix=_thumbs.jpg
      # shellcheck disable=SC2046
      ! ${inspect} \
        && test $(printf "%.0f" "$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${arg}")") -gt 3 \
        && {
          mtn -q -i -t \
            -D6 -b 0.6 \
            -r$(expr 5 - $# \& $# \< 4 \| 1) -c "${grid}" -w $((cols * 20)) \
            -W -O "${prefix}" -o "${suffix}" "${arg}" \
            || mtn -q -i -t \
              -W -O "${prefix}" -o "${suffix}" "${arg}"
        } \
        && timg -W "${prefix}/$(basename -- "${arg%.*}")${suffix}"
      ;;
    *\ image/*)
      timg="${timg}${arg}"
      command -v identify >/dev/null && continue
      ;;
    *\ inode/directory)
      ls="${ls}${arg}"
      test -L "${arg}" || continue
      ;;
    *)
      case "$(file --dereference "${arg}")" in
        *\ ?udio* | *\ ADTS,*)
          # TODO preconvert aac - |*\ ADTS\ *
          if ! ${inspect} && command -v audiowaveform >/dev/null; then
            img="${tmpfile}.png"
            case "${TERM}" in
              *-kitty)
                kitty=true
                audioheight=2
                ;;
              *)
                audioheight=5
                ;;
            esac
            find "${img}" -not -empty 2>/dev/null | grep --quiet . \
              || audiowaveform --quiet --pixels-per-second 2 --height 36 \
                --width 2000 --amplitude-scale auto --background-color 000000 \
                --waveform-color 99BBFF --axis-label-color 000000 \
                --input-filename "${arg}" --output-format png >"${img}" \
              && {
                test "${kitty}" && timg -g x"${audioheight}" "${arg}" \
                  && printf "\\033[${audioheight}A%$((audioheight * 3))s"
                timg -g x"${audioheight}" --auto-crop --upscale "${img}"
              }
          fi
          timga="${timga}${arg}"
          ;;
        *:\ *compress* | *\ archive*)
          list="${tmpfile}-list.txt"
          case "${arg}" in
            *.7z)
              test "$#" = 1 && 7z l "${arg}"
              ;;
            *.tar*)
              tar --list --file "${arg}"
              ;;
            *.zip*)
              unzip -l "${arg}"
              ;;
            *)
              if test "$#" = 1; then
                ${EDITOR:-vi} "${arg}"
              else
                case "${arg}" in
                  *.part) ;;
                  *)
                    (
                      nvim -es "+2w${list}|5,w>>${list}" "${arg}" \
                        || vim -s "+2w${list}|5,w>>${list}" "${arg}"
                    )
                    batplain="${batplain}${list}"
                    ;;
                esac
              fi
              ;;
          esac
          ;;
        *:\ SQLite\ *\ database*)
          # todo(2025-12-11):
          # for few tables: SELECT * FROM db LIMIT 3; | cut -c-$col
          hi "Tables" && sqlite3 "${arg}" ".tables"
          ;;
        *:\ data) ;;
        *\ key)
          bat="${bat}${arg}"
          continue
          ;;
        *)
          bat="${bat}${arg}"
          timga="${timga}${arg}"
          continue
          ;;
      esac
      ;;
  esac
  fileinfo "${arg}"
done

# timg: images
# timga: potentially viewable as image
# shellcheck disable=SC2046
if test "${timg}"; then
  # TODO don't show info on all images for gifs
  ${inspect} \
    || if command -v timg >/dev/null; then
      ${elevate} timg $(test "${timga}" && echo "-V") --rotate=exif -g "${cols}"x$((lines / 2)) \
        $(test "$#" -gt 1 \
          && echo "-t0.2 --auto-crop --center $(test "$#" -lt 20 && echo "--title") --grid=$(((grid < $# ? grid : $#) / 2))x") \
        "${timg}" "${timga}" 2>/dev/null || true
    else
      for img in ${timg}; do
        catimg -H $((lines / 2)) "${img}"
      done
    fi
  if command -v identify >/dev/null && (${inspect} || test "$#" -lt 10); then
    for img in ${timg}; do
      case "${img}" in
        *.gif) continue ;;
      esac
      ident="$(identify -ping -precision 3 -format "%wx%h %b %m %[bit-depth]-bit %[colorspace]" "${img}")"
      header=$(printf "%11s %-30s	%s\n" "${ident%% *}" "$(basename -- "${img}")" "${ident#* }")
      printf '\e[34m%b\e[0m' "${header}"
    done
  fi
fi

pager="${PAGER:-less -rF}"
# bat: unknown files
# batplain: files to print without header
if test "${bat}" -o "${batplain}"; then
  # TODO allow plain less
  test "$(bat --version | cut -d. -f2)" -gt 16 && rule=,rule
  if test "$#" -gt ${#bat} -a "$#" -gt ${#batplain} && test -z "${flags}"; then
    cut="--line-range :7"
    # batpager="cut -c-$(expr "$(cols)" \* 19 / 10 | cut -d. -f1)"
    batwidth=$((cols * 19 / 10))
    batwidth=$(batwidth | cut -d. -f1)
    # batpager="cut -c-$(${batwidth} | cut -d. -f1)"
    batpager="cut -c-${batwidth}"
  fi
  batcommand="${elevate} bat ${cut} ${flags} --pager"
  batstyle="--style plain${rule}"
  test "${batplain}" \
    && ${batcommand} "${batpager:-${pager}}" "${batstyle}" "${batplain}"
  test "${bat}" \
    && if test "${cut}" && ! "${inspect}"; then
      case "${TERM}" in
        *kitty)
          for file in ${bat}; do
            timgtxt=""
            txt="${prefix}/$(basename -- "${file}").txt"
            cp -- "${file}" "${txt}"
            timgtxt="${timgtxt}${txt}"
          done
          timg -V --grid=$((4 & ${#bat} > 5 | ${#bat})) --title="%b" \
            --frames=3 "${timgtxt}" \
            || head -n 3 "${timgtxt}"
          ;;
        *)
          for file in ${bat}; do
            ${batcommand} "${batpager:-${pager}}" "${batstyle}" "${file}"
            fileinfo "${file}"
          done
          ;;
      esac
    else
      if ! ${inspect}; then
        json=false
        if command -v cj >/dev/null; then
          json=true
          for file in ${bat}; do
            case "${file}" in
              *.json | *.geojson) ;;
              *) json=false ;;
            esac
          done
        fi
        if ${json}; then
          cj "${bat}"
        else
          # shellcheck disable=SC2086
          ${batcommand} "${batpager:-${pager}}" \
            ${batstyle},header"$(test "$#" -gt 1 && echo ",numbers")" "${bat}"
        fi
      fi
      if ${inspect} || test "$#" -lt "$((lines / 10))"; then
        fileinfo "${bat}"
      fi
    fi
fi

# shellcheck disable=SC2046,SC2086
if test "${ls}" -o "$#" -le $(echo "${flags}" | wc -w 2>/dev/null); then
  checkperm .
  if test -n "${readme}"; then
    # readme
    if [ -n "$1" ] && [ -f "$1" ]; then
      file="$1"
    elif [ "$#" -eq 0 ]; then
      file=$(find . -maxdepth 1 -iname 'readme*' -type f | head -n 1)
      # file=$(fd --max-depth=1 'readme(|.adoc|.md|.rdoc|.rst|.txt|.org)' | head -n 1)
    else
      file=$(find . -maxdepth 1 -iname 'readme*' -type f | head -n 1)
      # file=$(fd --max-depth=1 'readme|.md' | head -n 1)
    fi
    filepath="$(readlink -f "${file}")"
    extension="${file##*.}"
    case "${extension}" in
      [0-9]*) man "${filepath}" ;;
      *)
        if command -v glow >/dev/null 2>&1; then
          glow --style=ascii --width=$((cols - 10)) "${file}"
        elif command -v bat >/dev/null 2>&1; then
          bat --language=markdown --paging=auto --style=header \
            --terminal-width=$((cols - 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="${filepath}" \
            | man --local-file -
        else
          cat "${file}" | less -RF
        fi
        ;;
    esac
  else
    {
      if test -n "${tree}"; then
        ${elevate} tree -a --dirsfirst --du -h -C -L 3 "${flags}" -- "${ls:-.}"
      elif command -v lr 2>/dev/null >&2; then
        ${elevate} lr -GG -1l -oM -- "${ls:-.}"
      elif command -v eza 2>/dev/null >&2; then
        ${elevate} eza --color=always --long --group --classify \
          --all --all --sort=modified --reverse ${flags} -- "${ls:-.}"
      elif command -v gls 2>/dev/null >&2; then
        gls --color=always -La -lhF ${flags} -- "${ls:-.}"
      else
        ls --color=always -La -lhF ${flags} -- "${ls:-.}"
      fi
    } | "${pager}" --quit-if-one-screen
  fi
fi
