#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-

import os,sys,re
import urllib
from HTMLParser import HTMLParser
from urllib import FancyURLopener

# Start class myHTMLParser
class MyHTMLParser(HTMLParser):

    def __init__(self, pattern):
        HTMLParser.__init__(self)
        self.matcher = re.compile(pattern) 
        self.targets = []

    def handle_starttag(self, tag, attrs):
        for i in attrs:
            if "href" == i[0] and str(self.matcher.match(i[1])) != "None":
                self.targets.append(i[1])
# End class myHTMLParser

pivot = sys.argv[1].rfind("/")
url = (sys.argv[1])[:pivot]
localFile=sys.argv[2]

pivot += 1;
find = (sys.argv[1])[pivot:];
print "Looking for " + find
pattern = find + "[\w.-]*(\.tar\.gz|tar\.gz2|tgz|zip|exe)?"
parser = MyHTMLParser(pattern)

urlObject = FancyURLopener()
obj = urlObject.open(url)
parser.feed(obj.read())

if len(parser.targets) > 1:
    print "Could not resolve your download due to the number of hits."
    print "Refine your search."
    for i in parser.targets:
        print i

elif len(parser.targets) == 1:
    url += "/" + parser.targets[0]
    if os.path.exists(localFile): 
        print "File "+ localFile +" already exists and will not be downloaded..."
    elif parser.targets[0] == localFile:
        urllib.urlretrieve(url, localFile)
        print "Found: " + parser.targets[0]
    elif parser.matcher.match(localFile) != "None":
        urllib.urlretrieve(url,parser.targets[0]);
        print "Found: " + parser.targets[0]
    else:
        urllib.urlretrieve(url, parser.targets[0]);
        print "WARNING: the file found \'" + parser.targets[0] + "\' does not match \'" + localFile + "\'"
        print "Ensure the downloaded version is suitable."

else:
    print "No matches found!"

obj.close()
