#!/usr/bin/env sh
(test -d global && test -d $1) || {
	echo >&2 "($0) run [1m$me[21m from root of [1mlibk[21m source directory"
	exit 1
}

. global/common.sh
test "$OUT" = "" && {
	say "\$OUT environment variable must be set to your build directory - are you running this script by hand? run [1mmake doc[21m in the root directory instead!"
	exit 2
}

if ! has cmark; then
	say "to generate documentation for [1mlibk[21m, install the [1mcmark[21m package and try again"
	exit 3
fi


name=$1
mandest=$OUT/doc/man
out=$2
file=$name/$name.md
desc="$(grep -m1 "^$name:" global/modules | cut -d: -f4)"
date="$(date -r"$file" "+%d %A %Y")"

mkdir -p $mandest

echo  >$out ".TH ${name^^} \"$section\" \"$date\" \"hale.su libk [r$BUILD]\" \"modules\""

echo >>$out ".SH NAME"
echo >>$out "$name - $desc"
echo >>$out ".SH SYNOPSIS" 

dhead=$(grep -m1 -n "^# description$" $file)
if test $? -eq 0; then
	descline=$(echo "$dhead" | cut -d: -f1)
	offset=1
else
	descline=$(grep -m2 -n "^#" $file | tail -n1 | cut -d: -f1)
	offset=0
fi

tail -n+2 $file | head -n$(expr $descline - 2) | cmark -t man >> $out

echo >>$out ".SH DESCRIPTION"

tail -n+$(expr $descline + $offset) $file  | cmark -t man >> $out

say "wrote manpage for $name to $file"
