#!/usr/bin/env python

import os
import sys
import webbrowser

from os.path import abspath, basename, split, join, isdir, isfile

styles = """
<link rel="stylesheet" href="http://www.python.org/styles/styles.css" type="text/css"/>
<style type="text/css">
body { margin-left: 6em; margin-right: 6em; font-size: 95%; }
a { text-decoration: none; }
pre.literal-block, pre.doctest-block { margin-left: 0em; margin-right: 0em; }
</style>
"""

def readlines(filename, mode='rt'):
    file = open(filename, mode)
    try:
        return file.readlines()
    finally:
        file.close()

def apply_styles(outfile):
    outlines = readlines(outfile)
    f = open(outfile, 'wt')
    for line in outlines:
        if line.strip() == '</head>':
            f.write(styles)
        f.write(line)
    f.close()

def view_long_description(dirname):
    os.chdir(dirname)
    if not isfile('setup.py'):
        print >>sys.stderr, 'No setup.py found'
        return 1, ''
    outfile = abspath('.long-description.html')
    rc = os.system('"%s" setup.py --long-description | rst2html > "%s"' % (sys.executable, outfile))
    return rc, outfile

def view_file(filename):
    infile = abspath(filename)
    dirname, basename = split(filename)
    outfile = '.%s.html' % basename
    if dirname:
        outfile = join(dirname, outfile)
    outfile = abspath(outfile)
    rc = os.system('rst2html "%s" "%s"' % (infile, outfile))
    return rc, outfile

def main(args):
    if args:
        arg = args[0]
    else:
        arg = os.curdir

    if arg in ('-h', '--help'):
        print 'Usage: %s [eggdir|rstfile]' % basename(sys.argv[0])
        return 0

    if isdir(arg):
        rc, outfile = view_long_description(arg)
    elif isfile(arg):
        rc, outfile = view_file(arg)
    else:
        print >>sys.stderr, 'No such file or directory: %s' % arg
        return 1

    if rc == 0:
        apply_styles(outfile)
        webbrowser.open('file://%s' % outfile)
    return rc

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

