#!/bin/sh
search() {
	if [ "$QUERY_STRING" = "" ]
	then
		printf "10 Search for a POSIX man page\r\n"
		return
	fi

	result=$(find /usr/share/man/ -name "$QUERY_STRING.*p.gz" | head -n1)
	if [ -z "$result" ]
	then
		printf "51 No results\r\n"
		return
	fi

	result="$(basename -- "$result")"
	section="$(echo "$result" | cut -d. -f2 | cut -c1)"
	page="$(echo "$result" | cut -d. -f1)"

	printf "30 gemini://$SERVER_NAME$SCRIPT_NAME/$section/$page\r\n"
}

if [ "$PATH_INFO" = "" ] || [ "$PATH_INFO" = "/" ]
then
	search
	exit
fi

section="$(echo "$PATH_INFO" | cut -d/ -f2)"
page="$(echo "$PATH_INFO" | cut -d/ -f3)"

file="/usr/share/man/man$section/$page.${section}p.gz"
if ! [ -f "$file" ]
then
	printf "51 Not found\r\n"
	exit
fi

printf "20 text/plain\r\n"
man -T ascii -O width=72 -- "$section" "$page" | col -b
