#!/bin/sh

set -e

str isvalue "$MANUAL_DIR" \
	|| MANUAL_DIR=/usr/manual

# normalization
! str isvalue "$1" || str isvalue "$3" \
	&& printf "Usage: %s [name] (section)\n" "$argv0" 1>&2 \
	&& exit 1 \
	|| \
str isvalue "$2" && ! test -e "$MANUAL_DIR/$2/$1" \
	&& printf "%s: %s: No manual entry in section %s\n" "$0" "$1" "$2" \
		1>&2 \
	&& exit 1 \
	|| \
str isvalue "$2" \
	&& PAGE="$MANUAL_DIR/$2/$1" \
	|| for d in "$MANUAL_DIR"/*
			do test -e "$d/$1" && PAGE="$d/$1"
		done

# lookup + execution
! str isvalue "$PAGE" \
	&& printf "%s: %s: No manual entry\n" "$0" "$1" 1>&2 \
	&& exit 1 \
	|| \
! str isvalue "$SECTION_DIR" \
	&& printf "%s: %s: No manual entry\n" "$argv0" "$1" 1>&2 \
	&& exit 1 \
	|| \
<"$PAGE" groff -t -e -mandoc -Tascii
