#!/bin/sh

set -eu

VERSION="v0.1"

file=$1
[ -f "$file" ] || exit 1

name=$(basename "$file" .md)

awk -v name="$name" '
BEGIN {
    print ".TH \"" toupper(name) "\" 1"
    in_name = 0
}

function esc(s) {
    gsub(/\\/, "\\\\", s)
    gsub(/^\./, "\\&.", s)
    return s
}

function fmt(s) {
    while (match(s, /`[^`]+`/)) {
        pre = substr(s, 1, RSTART-1)
        mid = substr(s, RSTART+1, RLENGTH-2)
        post = substr(s, RSTART+RLENGTH)
        s = pre "\\fB" mid "\\fR" post
    }
    return esc(s)
}

{
    sub(/\r$/, "")

    if ($0 ~ /^# /) {
        section = substr($0, 3)

        if (toupper(section) == "NAME") {
            print ".SH NAME"
            in_name = 1
        } else {
            print ".SH " toupper(esc(section))
            in_name = 0
        }
        next
    }

    if ($0 ~ /^$/) {
        print ".PP"
        next
    }

    if (in_name) {
        split($0, a, " - ")
        if (length(a) > 1) {
            print "\\fB" esc(a[1]) "\\fR \\- " esc(a[2])
        } else {
            print "\\fB" esc($0) "\\fR"
        }
        next
    }

    if ($0 ~ /^- /) {
        sub(/^- /, "")
        split($0, a, "  ")
        print ".TP"
        print "\\fB" esc(a[1]) "\\fR"
        if (length(a) > 1) {
            print fmt(substr($0, length(a[1]) + 3))
        }
        next
    }

    print fmt($0)
}
' "$file"
