#!/usr/bin/env python

import os
import sys
import webbrowser

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

styles = """
<link rel="stylesheet" href="http://www.python.org/css/pypi.css" type="text/css"/>
<link media="screen" href="http://www.python.org/styles/screen-switcher-default.css" type="text/css" id="screen-switcher-stylesheet" rel="stylesheet"/>
<link media="screen" href="http://www.python.org/styles/netscape4.css" type="text/css" rel="stylesheet"/>
<link media="print" href="http://www.python.org/styles/print.css" type="text/css" rel="stylesheet"/>
<link media="screen" href="http://www.python.org/styles/largestyles.css" type="text/css" rel="alternate stylesheet" title="large text"/>
<link media="screen" href="http://www.python.org/styles/defaultfonts.css" type="text/css" rel="alternate stylesheet" title="default fonts"/>
<style type="text/css">
body {margin-left: 6em; margin-right: 6em; font-size: 95%;}
a {text-decoration: none;}
</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: view [eggdir|rstfile]'
        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:]))

