#!/usr/bin/env python
"""
This program requires the installation of python, and either python-creole
(1.0.4) or a combination of Genshi (0.6) and Creoleparser(0.7.4).  Please
replace all sys.path.append calls with the location of these programs if they
are not already in your path.

This program has four specified command line options and as many command line 
arguments as you care to send it (although at least one must be present).
A command line argument may be a directory, a .txt file, or the base name of
an existing .txt file. If the argument fulfills none of these criteria, an error
will be thrown.  If the argument is a directory, each .txt file within the 
directory will have a .html file named after it, and the directory will be given
a .css file named after it.  If the argument leads to a .txt file, that file 
will have a .html file and a .css file named after it.

-s/--style enables specification of the stylesheet this HTML will use.  Default
value is official.css, although a plain.css is provided as well.

-l/--logo enables specification of the logo in the upper left corner of the 
html output. Default value is chapel-logo.png for official.css and nothing for
plain.css

-c/--color enables specification of the header and sidebar box background color.
Default value is 005696 (a dark blue color) for official.css, CCCCCC (a light
gray color) for plain.css.  Can specify colors like purple or blue as well as
HTML color encoding (two digits each for r, g, b in hexadecimal)

-e/--embed indicates that the user wants the style sheet final version embedded 
within the HTML itself instead of within a separate file.
"""

def createHTML(file1, file2, style, embed):
    """ 
    Takes in the name of the .txt file and the name of the .html file to create,
    as well as the name of the stylesheet file used.
    """
    reader = open(file1, "r")
    writer = open(file2, 'w')
    
    string = reader.read()

    writer.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional")
    writer.write("//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-")
    writer.write("transitional.dtd\">")
    writer.write("\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n")
    writer.write("<head>\n")
    writer.write("<meta http-equiv=\"Content-Type\" content=\"text/html;")
    writer.write(" charset=utf-8\" />")
    """ HTML header (standard) """

    writer.write("<title>Chpldocs</title>\n")
    if embed:
        writer.write("<style type=\"text/css\">\n")
        styleReader = open(style, "r")
        writer.write(styleReader.read())
        writer.write("</style>\n")
        styleReader.close()
    else:
        writer.write("<link rel=\"stylesheet\" type=\"text/css\" ")
        writer.write("href=\"" + os.getcwd()  + "/" + style + "\" />\n")
    writer.write("</head>\n<body>\n")
    """ Style sheet and title """

    writer.write("<div id=\"wrapper\">")

    writer.write("<div id=\"headerBox\">\n<div id=\"headerTitle\">\n")
    writer.write("<h1 class=\"title\">")
    index = file1.rfind("/")
    writer.write(file1[index+1:-4])
    writer.write("</h1>\n</div>\n</div>")
    """ Header box and Header """

    writer.write("<div id=\"sidebar\">\n")

    directory = ""
    if index == -1:
        directory = os.getcwd()
    else:
        directory = file1[:index]
    for root, dirs, files in os.walk(directory):
        foldername = root[root.find(basedir) + len(basedir):]
        writer.write("<h5> " + foldername + "</h5>\n<ul>\n")
        for f in files:
            fullpath = os.path.join(root, f)
            if fullpath[-5:] == ".html":
                writer.write("<li><a href=\"")
                fullpath = os.getcwd() + "/" + fullpath
                writer.write(fullpath + "\">")
                index2 = fullpath.rfind("/")
                writer.write(fullpath[index2+1:-5] + "</a></li>\n")
        writer.write("</ul>\n")

    writer.write("</div>\n")
    """ Sidebar and links """

    writer.write("<div id=\"content\">\n")
    writer.write(creole2html(string.decode('utf-8')))
    writer.write("</div>\n")

    writer.write("</div>\n</body>\n</html>")

    reader.close()
    writer.close()

    # clean up the original .txt file
    os.unlink(file1)


def help():
    """ Prints out the help message for the user """
    print "Usage: chpldoc2html [directory | filename | filename.txt] .."
    print "\t-l <image>, --logo=<image> \tspecifies logo to be used"
    print "\t-s <stylesheet>, --style=<stylesheet> \tspecifieds stylesheet to be used"
    print "\t-c <color>, --color=<color> \t specifies color for sidebar and header"
    print "\t-e, --embed \tembeds stylesheet within .html output"


def makeStylesheet (style, logo, color, outputName):
    """ 
    Takes in the style sheet to (mostly use), the logo for the upper left corner
    and the color for the header box and sidebar.  Also takes in the name of the
    output file to write the changes to (so that the provided style sheet may
    be reused).
    """
    styleRead = open(style, "r")
    styleWrite = open(outputName, "w")            
    styleWrite.write(styleRead.read())
    styleRead.close()
    if len(logo) != 0:
       styleWrite.write("body {\n background-image:url(" + logo + ");\n")
       styleWrite.write("background-position:1em 1em;\n")
       styleWrite.write("background-repeat:no-repeat;\n}\n")
    if len(color) != 0:
       if color.startswith(('0','1','2','3','4','5','6','7','8','9')):
          styleWrite.write("#headerBox {\n background-color:#" + color + ";\n}\n")
          styleWrite.write("#sidebar {\n background-color:#" + color + ";\n}\n")
       else:
          styleWrite.write("#headerBox {\n background-color:" + color + ";\n}\n")
          styleWrite.write("#sidebar {\n background-color:" + color + ";\n}\n")
    styleWrite.close()

""" Script start follows """

import sys, getopt
import os
""" Creoleparser-0.7.4 version
    Note: in this version line breaks and horizontal lines do not pass HTML
    validation.  Creoleparser writes <hr> instead of <hr /> and <br> instead of
    <br />
"""
from creoleparser import creole2html

""" python-creole-1.0.4 version """
"""sys.path.append(os.environ['HOME'] + '/python-creole-1.0.4')
from creole import creole2html"""

""" Does os.environ['HOME'] work on Macs?  Windows? """

try:
   longargs = ["--logo=", "--style=", "--color=", "--embed"]
   opts, args = getopt.getopt(sys.argv[1:], "l:s:c:e", longargs)
except getopt.GetoptError:
   help()
   sys.exit()

style = os.environ['CHPL_HOME'] + "/util/docs/plain.css"
logo = ""
color = ""
embed = False

for opt, arg in opts:
   if opt in ("-l", "--logo"):
      logo = arg
   elif opt in ("-s", "--style"):
      style = arg
   elif opt in ("-c", "--color"):
      color = arg
   elif opt in ("-e", "--embed"):
      embed = True

if style == (os.environ['CHPL_HOME'] + "/util/docs/official.css") and logo == "":
        logo = os.environ['CHPL_HOME'] + "/compiler/etc/www/chapel-logo.png"

numArgs = len(args)
if numArgs == 0:
   help()
   sys.exit()
else:
   basedir = ""
   i = 0
   while i < numArgs:
         if (os.path.isdir(args[i])):
            if args[i][-1] == "/":
                stylesheet = args[i] + args[i][args[i][:-1].rfind("/")+1:-1]
            else:
                stylesheet = args[i] + "/" + args[i][args[i].rfind("/")+1:]
            
            if embed:
                stylesheet += "-tmp"
            stylesheet += ".css"
            

            makeStylesheet(style, logo, color, stylesheet)
            
            
            for root, dirs, files in os.walk(args[i]):
                for f in files:
                    fullpath = os.path.join(root, f)
                    if fullpath[-4:] == ".txt":
                       tmp = open(fullpath[:-3] + "html", "w")
                       tmp.close()
                    """ 
                    This for loop is run so that the sidebar will show all
                    the html files that it creates in the following loop
                    """
            
        
            for root, dirs, files in os.walk(args[i]):
                basedir = root
                for f in files:
                    fullpath = os.path.join(root, f)
                    if fullpath[-4:] == ".txt":
                        createHTML(fullpath, fullpath[:-3] + "html", stylesheet, embed)
            if embed:
                os.remove(os.getcwd() + "/" + stylesheet)
         elif (os.path.isfile(args[i])):
            stylesheet = args[i][:-4] 
            if embed:
                stylesheet += "-tmp"
            stylesheet += ".css"
            
            makeStylesheet(style, logo, color, stylesheet)

            index = args[i].rfind("/")
            basedir = args[i][:index]

            createHTML(args[i], args[i][:-3] + "html", stylesheet, embed)
            if embed:
                os.remove(os.getcwd() + "/" + stylesheet)

         elif (os.path.isfile(args[i] + ".txt")):
            stylesheet = args[i]
            if embed:
                stylesheet += "-tmp"
            stylesheet += ".css"
            
            index = args[i].rfind("/")
            basedir = args[i][:index]

            makeStylesheet(style, logo, color, stylesheet)
            createHTML(args[i] + ".txt", args[i] + ".html", stylesheet, embed)
    
            if embed:
                os.remove(os.getcwd() + "/" + stylesheet)
         else:
            print args[i]
            help()
            sys.exit(2)
         i += 1

