#!/bin/sh

m=$(printf %s "$QUERY_STRING" | sed -e "s/m=//" -e "s/+/ /g")
manfile=$(man -w $m)

if [ -z "$m" ]; then
    printf "Content-type: text/html\r\n"
    printf "\r\n"
    printf "<!DOCTYPE html>\r\n"
    printf "<html>\r\n"
    printf "<head><title>man2html</title></head>\r\n"
    printf "<body>\r\n"
    printf '<form method="GET">\r\n'
    printf "<label>manpage search</label>\r\n"
    printf '<input autofocus name="m" type="text">\r\n'
    printf "</form>\r\n"
    printf "</body>\r\n"
    printf "</html>\r\n"
    exit 1
fi

if [ ! -f "$manfile" ]; then
    printf "Content-type: text/plain\r\n"
    printf "\r\n"
    printf "manpage for %s not found\n" "$m"
    exit 1
fi

zcat -f "$manfile" \
    | man2html -M /~ben/cgi-bin/man.sh

exit 0
