#!/bin/sh
#
# he - print brief help about a single option or command
#
# usage:
# he bash continue
# he rsync -v
#
# ---
# source: https://github.com/mikelward/scripts

usage() {
  cat <<EOF 1>&2
Usage: $(basename "$0") {<command> or -} [<option|section>]
Example:
    he bash getopts (shows documentation for bash getopts)
    he ssh -v       (shows documentation for ssh -v flag)
    he select       (shows SYNOPSIS for select(2))
    he 'open(2)'    (shows SYNOPSIS for open(2))
    adb help | he - install    (shows documentation for adb install)
EOF
}

if test "$#" -lt 1; then
  usage
  exit 2
fi

manpage="$1"
# show the SYNOPSIS section if no section or option was given
option="${2:-SYNOPSIS}"

# section=${manpage#"$page"}
# section=${manpage#$page}

# handle manpage(number)
# shellcheck disable=SC2249
case ${manpage} in
  *\(*\))
    page=${manpage%\(*\)}
    section=${manpage#"${page}"}
    section=${section#\(}
    section=${section%\)}
    manpage=${page}
    ;;
esac

# GROFF_FONT_PATH=(/opt/homebrew/Cellar/groff/1.23.0_1/share/groff/1.23.0/font:/usr/lib/font)
# shellcheck disable=SC2086,SC2250
# GROFF_NO_SGR=1 MANROFFOPT="-c" man ${section:+-s ${section}} "${manpage}" | perl -n -e '

he() {
  perl -n -e '
BEGIN {
    $option = "'$option'";
    $inside_option = 0;
}
if (!$inside_option) {
    if (/^(\s*)\Q$option\E\b/p) {
        # start of this option
        $option_indentation = $1;
        $inside_option = 1;
        $saw_blank_line = 0;
        print;
    }
} else {
    if (/^$/) {
        $saw_blank_line = 1;
        print;
    } elsif (/^\Q$option_indentation\E\S/ and $saw_blank_line) {
        # item at same indentation => start of next option
        $inside_option = 0;
    } elsif (/^\S/) {
        # new heading => start of next section
        $inside_option = 0;
    } else {
        print;
    }
}
'
}

if test "${manpage}" = "-"; then
  he
else
  man ${section:+-s ${section}} "${manpage}" | he
fi
