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

source global/common.sh
reqpack cmark "generate documentation"
check gen "a directory for generated build dependencies"

file="$1"
filename="$(basename "$file")"
stem=${filename%%.md}

mandest=${manpage_to:-"$to/doc/man"}
htmldest=${html_to:-"$to/doc/html"}
pdfdest=${pdf_to:-"$to/doc/pdf"}

section=${manual_section:-4}
man="$mandest/$stem.$section"
html="$htmldest/$stem.html"
pdf="$pdfdest/$stem.pdf"
fmt="$gen/$stem.tmp"

desc_rec="$(grep -m1 "^$stem:" global/modules)"
if test "$desc_rec" != ""; then
	desc=" - $(echo $desc_rec | cut -d: -f4)"
else
	desc=""
fi
date="$(date -r"$file" "+%d %A %Y")"


echo  >"$fmt" ".TH ${stem^^} \"$section\" \"$date\" \"hale.su libk [r$build]\" \"modules\""

echo >>"$fmt" ".SH NAME"
echo >>"$fmt" "$stem$desc"
echo >>"$fmt" ".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 --smart -t man >>"$fmt"

echo >>"$fmt" ".SH DESCRIPTION"

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

test "$doc_html" = "yes" && {
	mkdir -p "$htmldest"
	groff -Thtml -Kutf8 -m man "$fmt" > "$html"
	test "$verbose" != "loud" ||
	say "wrote html page for $stem to $html"
}

test "$doc_pdf" = "yes" && {
	mkdir -p "$pdfdest"
	groff -Tpdf  -Kutf8 -m man "$fmt" > "$pdf"
	test "$verbose" != "loud" ||
	say "wrote pdf for $stem to $pdf"
}

test "$doc_man" = "yes" && {
	mkdir -p "$mandest"

	if has gzip; then
		man="$man.gz"
		gzip -c -f "$fmt" > "$man"
	else
		mv "$fmt" "$man"
	fi

	test "$verbose" != "loud" ||
	say "wrote manpage for $stem to $man"
}
