#!/usr/bin/env bash
#
# Generate asciidoc manpage markup from Cogito script header.
# Copyright (c) Jonas Fonseca, 2005
#
# Takes a path to a Cogito script. Prints the manpage to stdout.

command=$1

if [ ! -e "$command" ]; then
	echo "$command does not exist" >&2
	exit
fi

COMMAND=$(basename $command)

# FIXME: Show the SHA1 of the command below the TITLELINE.

# Generate the 'CG-COMMAND(1)' title from cg-command
TITLE="$COMMAND(1)"
# Asciidocs wants the title line ('====') to be as wide as the title.
TITLELINE=$(echo "$TITLE" | sed 's/[0-9a-zA-Z()-]/=/g')

# Get `USAGE="cg-command args..."` line and make it `cg-command args...`
SYNOPSIS=$(sed -n '/^USAGE=/,0s/^USAGE="\(.*\)"/\1/p' < $command)

# Extract the script header.
HEADER=$(sed -n '3,/^$/s/^# *//p' < $command)

# Some scripts have copyright lines followed by 'Based on script by ...' lines.
# Include them so they are also put in the COPYRIGHT section.
COPYRIGHT=$(echo "$HEADER" | sed -n '/^Copyright (c)/,/^$/p' \
			   | sed 's/(c)/(C)/')

# First line of the header contains the caption. Normalize it by lowercasing the
# start and stripping any punctuation.
CAPTION=$(echo "$HEADER" | head -n 1 | tr '[A-Z]' '[a-z]' | sed 's/\.$//')

# Get remaining sections and carefully insert links to cogito commands when they
# were referenced as "`cg-command`". This way references from cg-* combos in
# code listings will be ignored.
BODY=$(echo "$HEADER" | sed '0,/^$/d' \
		      | sed 's/`\(cg-[a-z-]\+\)`/gitlink:\1[1]/')

DESCRIPTION=
OPTIONS=
MISC=

section=$(echo "$BODY" | sed -n '1,/^-[-]*-$/p')
section_lines=$(echo "$section" | wc -l)
lines=$(echo "$BODY" | wc -l)

if [ $section_lines = $lines ]; then
	DESCRIPTION="$BODY"

else
	section_end=$(($section_lines - 2))
	DESCRIPTION=$(echo "$BODY" | sed -n "1,${section_end}p")
	BODY=$(echo "$BODY" | sed -n "$((section_lines - 1)),\$p")

	if [ "$(echo "$BODY" | head -n 1)" = "OPTIONS" ]; then
		BODY=$(echo "$BODY" | sed -n '3,$p')
		section=$(echo "$BODY" | sed -n "1,/^-[-]*-\$/p")
		section_lines=$(echo "$section" | wc -l)
		lines=$(echo "$BODY" | wc -l)

		if [ $section_lines = $lines ]; then
			OPTIONS="$BODY"
		else
			section_end=$(($section_lines - 2))
			OPTIONS=$(echo "$BODY" | sed -n "1,${section_end}p")
			MISC=$(echo "$BODY" | sed -n "${section_end},\$p")
		fi

	else
		MISC="$BODY"
	fi
fi

cat <<__END__
$TITLE
$TITLELINE

NAME
----
$COMMAND - $CAPTION

SYNOPSIS
--------
$SYNOPSIS

DESCRIPTION
-----------
$DESCRIPTION

OPTIONS
-------
$OPTIONS

-h, --help::
	Print usage help.

$MISC

COPYRIGHT
---------
$COPYRIGHT

SEE ALSO
--------
$COMMAND command is part of gitlink:cogito[7],
a toolkit for managing gitlink:git[7] trees.
__END__
