#!/bin/bash
# vim: softtabstop=2 shiftwidth=2 expandtab

cleanup() {
  tput clear
}

# shellcheck disable=SC1091
sources=(
  /lib/profiling-lib.sh
  /etc/zfsbootmenu.conf
  /lib/kmsg-log-lib.sh
  /lib/zfsbootmenu-core.sh
  /lib/zfsbootmenu-ui.sh
)

for src in "${sources[@]}"; do
  # shellcheck disable=SC1090
  if ! source "${src}" >/dev/null 2>&1 ; then
    echo "<3>ZFSBootMenu: unable to source '${src}' in $0" > /dev/kmsg
    exit
  fi
done

unset src sources

trap cleanup EXIT INT TERM

# zfsbootmenu-help invokes itself, so the value of $WIDTH depends
# on if $0 is launching fzf (-L) or is being launched inside
# fzf (-s).

WIDTH="$( tput cols )"
PREVIEW_SIZE="$(( WIDTH - 28 ))"
[ ${PREVIEW_SIZE} -lt 10 ] && PREVIEW_SIZE=10

[ -z "${FUZZYSEL}" ] && FUZZYSEL="fzf"

help_pager() {
  WANTED="${1}"

  SORTED=()
  for SECTION in "${SECTIONS[@]}"; do
    if ! [[ $SECTION =~ ${WANTED} ]]; then
      SORTED+=("${SECTION}")
    else
      FINAL="${SECTION}"
    fi
    done
  SORTED+=("${FINAL}")

  header="$( column_wrap "\
[PAGEDN] scroll down
[PAGEUP] scroll up
[ESCAPE] back
")"

  printf '%s\n' "${SORTED[@]}" | ${FUZZYSEL} \
    --prompt 'Topic > ' \
    --with-nth=2.. \
    --bind pgup:preview-up,pgdn:preview-down \
    --preview="$0 -s {1}" \
    --preview-window="right:${PREVIEW_SIZE}:wrap${HAS_BORDER:+,border-sharp}" \
    --header="${header}" \
    ${HAS_BORDER:+--border=top} \
    ${HAS_BORDER:+--color=border:white} \
    ${HAS_BORDER:+--border-label="$( global_header )"} \
    --tac --inline-info --ansi --layout="reverse-list" || true
}

doc_base="/usr/share/docs/help-files"

# shellcheck disable=SC2012
for size in $( ls "${doc_base}" | sort -n -r ) ; do
  if [ "${PREVIEW_SIZE}" -ge "${size}" ]; then
    doc_path="${doc_base}/${size}"
    break
  fi
done

if [ -z "${doc_path}" ]; then
  # shellcheck disable=SC2012
  doc_path="${doc_base}/$( ls "${doc_base}" | sort -n | head -1 )"
fi

for doc in "${doc_path}"/* ; do
  SECTIONS+=( "${doc} $( head -1 "${doc}" )" )
done
SECTIONS+=( "zreport $( colorize white 'System Report' )" )

while getopts "lL:s:" opt; do
  case "${opt}" in
    l)
      printf '%s\n' "${SECTIONS[@]}"
      exit
      ;;
    L)
      help_pager "${OPTARG}"
      exit
      ;;
    s)
      if [ "${OPTARG}" == "zreport" ]; then
        /libexec/zfunc zreport
      else
        cat "${OPTARG}"
      fi
      exit
      ;;
    ?)
      exit
      ;;
    *)
      exit
      ;;
  esac
done

# No options detected, show the main help section
help_pager "main-screen"
