#!/bin/sh -e
#
# mansec - interactively choose and open a man page from a specific section
# dependencies: fzf/fuzzel
#
# usage: mansec <section> (0p, 1p, 3p, and so on ...)
# menu opts 

OPTS="-i -b -l 4"
alias nl="nl -s '' -n ln"

[ -n "${DISPLAY}" ] \
  && menu="fuzzel --dmenu ${OPTS}" \
  || menu="fzf"

# if no section is specified then interactively choose from the list
[ -n "$1" ] && SEC="($1)" \
  || SEC="$(man -k . | cut -d ' ' -f 2 | sort | uniq | nl \
    | ${menu} --prompt Section | awk '{ print $NF }')"

if tmux -q has-session 2>/dev/null; then
  term="tmux new-window"
else
  term="terminal"
fi

man -k . | awk -v q="${SEC}" '$2 == q { print }' | nl \
  | ${menu} --prompt "${SEC}" \
  | awk '{ sub("\\(",""); sub("\\)",""); print $3 " " $2 }'
  # | xargs "${term}" man
