#!/usr/bin/env sh

man="$1"
section="$2"

if [ -z "$man" ] || [ -z "$section" ]; then
    echo "Usage: $0 <man> <section>"
    exit 1
fi

file="man/man${section}/${man}.${section}"

if [ -f "$file" ]; then
    echo "File $file already exists. Move it out of the way."
    exit 1
fi

(
    mdocdate=$(date "+%B %d %Y")
    uppercase=$(echo "$man" | tr '[:lower:]' '[:upper:]')

    printf '.Dd $%s: %s $\n' "Mdocdate" "${mdocdate}"
    echo ".Dt ${uppercase} ${section}"
    echo ".Os Telodendria Project"
    echo ".Sh NAME"
    echo ".Nm ${man}"
    echo ".Nd {SET DESCRIPTION HERE}"

    if [ "$section" = "3" ]; then
        echo ".Sh SYNOPSIS"
        echo ".In ${man}.h"
    fi

    echo ".Sh DESCRIPTION"

    if [ "$section" = "3" ]; then
        echo ".Sh RETURN VALUES"
    fi

    echo ".Sh SEE ALSO"
) > "$file"

$EDITOR "$file"