#!/usr/bin/env python
import cgi, urllib, sys
#import cgitb

version = '0.9.1'
year = '2004'
vendor = 'WHGDev'

def error(about, title, text):
    return """<html>
    <head>
    <title>""" + title + """</title>""" + stylesheet() + """</head>
    <body><div class="main"><b>""" + about + """</b><br>""" + text + """</div>
    <div class="space">""" + ver() + """</body>
    </html>"""

def ver():
    """Returns the version"""
    return 'relocate ' + version + ' GPLd ' + year + ' by ' + vendor

def stylesheet():
    """Returns the stylesheet"""
    return """<style type="text/css">
    body {
        font-size: 75%;
        color: #000000;
        background: #FFFFFF;
        margin-top: 1em;
        margin-left: 5%;
        margin-right: 5%;
        font-weight : normal;
        font-style : normal;
        text-decoration : none;
    }

    .main {
        color: #000000;
        background: rgb(236,233,213);
        margin-top: 0;
        margin-bottom: 0;
        margin-left: 5%;
        margin-right: 5%;
        padding: 0.5em;
        border: 2px solid black;
    }

    .center {
        width: auto;
        margin-top: 0;
        margin-bottom: 0;
        margin-left: auto;
        margin-right: auto;
        text-align: center;
    }

    img {
        border: none;
    }

    table, td {
        font-size: 100%;
        margin-left: auto;
        margin-right: auto;
    }

    body, p, h1, h2, h3, table, td, th, ul, ol {
        font-family: verdana, helvetica, arial, sans-serif;
    }

    li {
        margin-bottom: 0.5em;
        padding: 0;
    }

    .links li { margin-bottom: 0; }

    ul, ol {
        list-style-type: none;
        margin-top: 0;
        margin-bottom: 0;
        margin-left: 0;
        padding: 0;
    }

    .componentlist {
        list-style-type: none;
        padding-left: 0;
        margin-top: 0;
        margin-bottom: 0;
        margin-left: 0.5em;
    }

    .bulletlist {
        list-style-type: square;
        padding-left: 0;
        margin-top: 0;
        margin-bottom: 1em;
        margin-left: 1.5em;
    }

    .bulletlist li { margin-bottom: 0; }

    .oneline {
        display: inline;
        margin-left: 0.1em;
        margin-right: 0.1em;
    }

    h1 {
        margin-top: 0;
        margin-bottom: 0.5em;
        background-color: transparent;
        color: #000000; 
    }

    h2 {
        margin-top: 0;
        margin-bottom: 0;
        background-color: transparent;
        color: #000000; 
    }

    h3 {
        margin-top: 0;
        margin-bottom: 0.5em;
        background-color: transparent;
        color: #000000; 
    }

    h4 {
        margin-top: 0.5em;
        margin-bottom: 0;
        background-color: transparent;
        color: #000000; 
    }

    h1 { font-size: 150%; }
    h2 { font-size: 100%; }
    h3 { font-size: 100%; }
    h4 { font-size: 100%; }
    h5 { font-size: 90%; }
    h6 { font-size: 80%; }

    hr {
        background-color: transparent;
        margin-top: 1em;
        margin-bottom: 1em;
        color: #000000;
        height: 1px;
    }

    .space {
        color: #000000;
        width: auto;
        height: 2px;
        padding: 0;
        margin-left: 0;
        margin-right: 0;
        margin-top: 1.5em;
        margin-bottom: 1.5em;
    }

    .innerspace {
        color: #000000;
        width: auto;
        height: 1px;
        padding: 0;
        margin-left: 0;
        margin-right: 0;
        margin-top: 1em;
    }

    a:link    { color: #b27854; background-color: transparent; text-decoration: underline; }
    a:visited { color: #b27854; background-color: transparent; text-decoration: underline; }
    a:active  { color: #000000; background-color: transparent; text-decoration: underline; }
    a:hover   { color: #808080; background-color: #DDDDDD; text-decoration: underline; }

    span.note {
        font-size: 95%;
    }
    </style>"""

def initpage(mime="text/plain", disposition=None):
    """This function prepares the HTTP Connection to
    send proper headers - content type and content disposition"""
    print 'Content-Type: %s' % mime
    if disposition != None:
        # we got some content dispositon
        print 'Content-Disposition: attachment; filename="%s"' % disposition
    print
    

def getfile(url):
    """Opens a remote file and returns a tuple with
    a file-like object and with the content type"""
    try:
        # open the file
        remote = urllib.urlopen(url)
        # get the content type
        mime = remote.headers.gettype()
        return (remote, mime)
    except IOError:
        # Well, no such file found
        raise IOError('No such file or directory')

def main():
    #cgitb.enable()
    # get the HTTP GET Arguments
    form = cgi.FieldStorage()
    
    # get url field
    try:
        url = form['url'].value
    except KeyError:
        url = None
    
    # get extension field
    try:
        ext = form['ext'].value
    except KeyError:
        ext = None
    
    if not url or not ext:
        initpage('text/html')
        print error(
            "Arguments missing", 
            "Too less arguments given, Sai", 
            "You need to specify both url and ext arguments.")
        sys.exit(100)
    
    # now get the names
    import os.path
    fileprefix = os.path.splitext(os.path.basename(url))[0]
    ext = '.' + ext
    dispositionname = fileprefix + ext
    # now dispositionname is the new name of the file with the new suffix
    
    # okay, let's start work!
    try:
        # we try to get that URL
        remotefile = getfile(url)
        
        # well done, now initialise the page with the proper
        #+Content Type (determined by the content type of the URL)
        #+and the proper conten disposition
        initpage(mime=remotefile[1], disposition=dispositionname)
        
        if sys.platform == "win32":
            # well, on Windows systems the stdout does not really like binary
            #+so we need to switch the stdout to binary mode
            import os, msvcrt
            msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
        
        # all prerequisites done, lets start loading the file
        sys.stdout.write(remotefile[0].read())
        
    except IOError:
        # no such file found
        initpage('text/html')
        print error("File not found",
            "No such file, Sai",
            "File %s was not found, check it exists." % url)

if __name__ == '__main__':
    main()