#!/bin/bash -e

CON_COMPAT="0.3.2" PATH="${PATH}:/usr/share/con-dev" . con-lib.bash
con::include opt staging

con_opt::init "Generate reStructured text (RST), trimmed for use as manual page, from bash code."
con_opt::add -aDOC_PREFIX -d"RST" "P" "Documentation prefix."
con_opt::add -aAUTHOR             "a" "Add author name and/or email address."
con_opt::add -aDATE               "d" "Add date string."
con_opt::add -aCOPYRIGHT          "c" "Add copyright text."
con_opt::add -aVERSION            "n" "Add version nummber."
con_opt::add -aSECTION            "s" "Add man section."
con_opt::add -aGROUP              "g" "Add man group."
con_opt::pos:add -Tfile "FILE.bash" "Bash code file."
con_opt::parse "${@}"

con_lib2rst()
{
	local bashFile="$(con_opt::pos:get 0)"
	local bashFileBase="$(basename "${bashFile}")"
	local prefix="$(con_opt::get "P")"
	local prefixRegex="^# ${prefix}:"
	local prefixLen=$((${#prefix}+5))

	# Header line marking the manual's ID
	con::printLine = ${#bashFileBase}
	printf "%s\n" "${bashFileBase}"
	con::printLine = ${#bashFileBase}

	# First three lines: Title. Need to be double underlined using "-"
	head --lines=3 "${bashFile}" | { grep "${prefixRegex}" || true; } | cut --characters="${prefixLen}-"

	# Add manual config: Gets transferred to the correct places in the man
	! con_opt::given a || printf ":Author: %s\n"         "$(con_opt::get "a")"
	! con_opt::given d || printf ":Date: %s\n"           "$(con_opt::get "d")"
	! con_opt::given c || printf ":Copyright: %s\n"      "$(con_opt::get "c")"
	! con_opt::given n || printf ":Version: %s\n"        "$(con_opt::get "n")"
	! con_opt::given s || printf ":Manual section: %s\n" "$(con_opt::get "s")"
	! con_opt::given g || printf ":Manual group: %s\n"   "$(con_opt::get "g")"
	printf "\n"

	# Add all the rest RST code found in file
	tail --lines=+4 "${bashFile}" | { grep --text "${prefixRegex}" || true; } | cut --characters="${prefixLen}-"
}

con_lib2rst
