#!/usr/bin/python
############################################################################
# Copyright (C) 2003  Klaus Reimer <k@ailis.de>
#
# $Id: djbdoc2man.in,v 1.4 2004/04/12 18:26:45 k Exp $
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place, Suite 330, Boston, MA 02111-1307 USA
############################################################################

import getopt
import string
import sys
import re


# Set globals
VERSION = "1.1"
NAME = "djbdoc2man"

# print usage informations in help2man compatible form
def print_help():
    print "Usage:", NAME, "[OPTIONS]"
    print "Converts html documentation pages from http://cr.yp.to/ to manual pages."
    print ""
    print "  -p, --package=NAME  Use NAME as package name (i.e. Daemontools)"
    print "  -v, --pversion=VER  Use VER as package version (i.e. 0.76)"
    print "  -s, --section=SEC   Use SEC as manual section (Defaults to 1)"
    print "  -n, --name=NAME     Override option. Use NAME as program name"
    print "  -y, --syntax=LINE   Override option. Use LINE as syntax line"
    print "  -h, --short=TEXT    Override option. Use TEXT as short desctiption"
    print "  -q, --quiet         Suppress warning messages"
    print "  -h, --help          Display help and exit"
    print "  -V, --version       Display version and exit"
    print ""
    print "This utility converts html documentation pages from D. J. Bernstein"
    print "(http://cr.yp.to/) to manual pages. Just pipe in the HTML page and you'll"
    print "get a manual page on stdout."
    print ""
    print "Report bugs to Klaus Reimer <k@ailis.de>"
    print ""
    
# Print version informations in help2man compatible form
def print_version():
    print NAME, VERSION
    print ""
    print "Copyright (C) 2003  Klaus Reimer <k@ailis.de>"
    print "This is free software; you can redistribute it and/or modify it under"
    print "the terms of the GNU General Public License as published by the Free"
    print "Software Foundation; either version 2 of the License, or (at your"
    print "option) any later version."
    
# Converts HTML tags to manpage tags.
def format(text):
    text = string.replace(text, "<i>", "\\fI")
    text = string.replace(text, "</i>", "\\fR")
    text = string.replace(text, "<h2>", "\n\n\\fB")
    text = string.replace(text, "</h2>", "\\fR\n")
    text = re.sub("</[uo]l>", ".LP", text)
    text = re.sub("<li>(.*?):[\s]*", ".TP\n\\1\n", text)
#    text = re.sub("<h2>[\s]*(.*?)[\s]*</h2>[\s]*", ".br.br\n\\fB\\1\\fR.br\n", text)
    text = re.sub("<.*?>", "", text)
    text = string.replace(text, "&gt;", ">")
    text = string.replace(text, "&lt;", "<")
    text = string.replace(text, "&amp;", "&")
    return text
    
# Initialize variables
section = 1
package_name = ""
package_version = ""
override_name = ""
override_syntax = ""
override_short = ""
quiet = 0
    
# Process command line arguments
try:
    opts, args = getopt.getopt(sys.argv[1:], "hVn:p:v:y:h:s:q", 
        ["help", "version", "name=", "package=", "pversion=", "syntax=", "short=", "section=", "quiet"])
except getopt.GetoptError:
    print_help()
    sys.exit(1)
for opt, arg in opts:
    if opt in ("-V", "--version"):
        print_version()
        sys.exit(1)
    if opt in ("-h", "--help"):
        print_help()
        sys.exit(1)
    if opt in ("-n", "--name"):
        override_name = arg
    if opt in ("-y", "--syntax"):
        override_syntax = arg
    if opt in ("-p", "--package"):
        package_name = arg
    if opt in ("-v", "--pversion"):
        package_version = arg
    if opt in ("-s", "--section"):
        section = arg
    if opt in ("-h", "--short"):
        override_short = arg
    if opt in ("-q", "--quiet"):
        quiet = 1

# Read HTML page from stdin
html = ""
block = sys.stdin.read(8192)
while len(block):
    html = html + block
    block = sys.stdin.read(8192)

# Retrieve program name
if override_name == "":
    match = re.compile("<h1>[\s]*The[\s]*[\s]*(.*?)[\s]*[\s]*program[\s]*</h1>").search(html)
    if not match:
        sys.stderr.write("ERROR: Unable to retrieve program name. Please override with -n.\n")
        sys.exit(1)
    name = format(match.group(1))
else:
    name = override_name    
    
# Retrieve syntax line
if override_syntax == "":
    match = re.compile("<h2>[\s]*Interface[\s]*</h2>[\s]*<pre>[\s]*(.*?)[\s]*</pre>").search(html)
    if not match:
        match = re.compile("</h1>[\s]*<pre>[\s]*(.*?)[\s]*</pre>").search(html)
    if not match:
        if quiet == 0:
            sys.stderr.write("WARNING: Unable to retrieve syntax line. Please override with -s. Using name as syntax line for now.\n")
        syntax = name
    else:
        syntax = match.group(1)
else:
    syntax = override_syntax 
    
# Retrieve short description text
if override_short == "":
    match = re.compile("</h1>.*?<tt>[\s]*%s[\s]*</tt>[\s]*(.*?)[\s]*<h2>" % (name), re.DOTALL).search(html)
    if not match:
        if quiet == 0:
            sys.stderr.write("WARNING: Unable to retrieve short description text. Please override with -h. Using name as short description for now.\n")
        short = name
    else:
        short = "%s - %s" % (name, match.group(1))
else:
    short = "%s - %s" % (name, override_short)
    
# Retrieve description text
match = re.compile("<h2>[\s]*Interface[\s]*</h2>[\s]*<pre>.*?</pre>(.*)[\s]*</body>", re.DOTALL).search(html)
if not match:
    match = re.compile("<h2>[\s]*Interface[\s]*</h2>[\s]*(.*)[\s]*</body>", re.DOTALL).search(html)
if not match:
    match = re.compile("</h2>[\s]*(.*)[\s]*</body>", re.DOTALL).search(html)
if not match:
    match = re.compile("</pre>[\s]*(.*)[\s]*</body>", re.DOTALL).search(html)
if not match:
    match = re.compile("</h1>[\s]*(.*)[\s]*</body>", re.DOTALL).search(html)
if not match:   
    sys.stderr.write("ERROR: Unable to retrieve description. Plese make sure this is a DJB documentation\n")
    sys.stderr.write("html page. If you are sure please contact the author: Klaus Reimer <k@ailis.de>\n")
    sys.exit(1)

description = match.group(1)

# Output manual page
print ".TH \"%s\" \"%d\" \"%s\" \"\" \"%s\"" % (name, section, package_version, 
    package_name)
print ".SH \"NAME\""
print ".LP"
print format(short)
print ".SH \"SYNTAX\""
print ".LP"
print format(syntax)
print ".SH \"DESCRIPTION\""
print ".LP"
print format(description)

print ".SH \"AUTHORS\""
print ".LP"
print "Written by D. J. Bernstein."
print ""
print "This manual page has been locally created by Klaus Reimer's"
print "<k@ailis.de> djbdoc2man program and is not part of the Debian"
print "Project. The content of this manual page has been automatically"
print "extracted from D. J. Bernstein's documentation pages on"
print "http://cr.yp.to/."
print ""
print "Please note that you may not distribute this manual page without"
print "permission of the original author."

