#!/usr/bin/python2.2
import os, re, cPickle, Queue

import threading
from config import dir, odir
from shutil import copyfile

num_threads = 5
debug = 0

# now try to run uscan in a tmp dir with a bogus changelog
class find_update(threading.Thread):
    def __init__(self):
        self.has_warning = 0
        sem.acquire()
        self.tmpdir = os.tempnam('/tmp', 'PTS_') #ok, insecure blahblah
        self.tmpdir = self.tmpdir + '/'

        os.mkdir(self.tmpdir)
        os.mkdir(self.tmpdir + 'debian') #our faked debian/ dir
    
        self.pkg = q.get()
        self.hash = self.pkg[0]
        if self.pkg[0:3] == "lib":
            self.hash = self.pkg[0:4]
        threading.Thread.__init__(self)

    def run(self):
        print "%s/%s/%s/watch" % (odir, self.hash, self.pkg)
        copyfile("%s/%s/%s/%s/watch" % (curdir, odir, self.hash, self.pkg), self.tmpdir + 'debian/watch')
        fch = open(self.tmpdir + 'debian/changelog', 'w+')

        fch.write(
"""%s (%s) unstable; urgency=low
  * this is a fake entry
 -- PTS watch update <pts@qa.debian.org>  Sat, 11 Jan 2003 17:56:41 +0100
""" % (self.pkg, watch[self.pkg]['version']) )
        fch.close()

        os.chdir(self.tmpdir)
    
        uscan = os.popen("/usr/bin/uscan --no-download 2>&1")
        for line in uscan.readlines():
            if debug: print line
            r = re.search("Warning: (.*)", line)
            if r:
                self.has_warning = 1
                watch[self.pkg]['warning'] = watch[self.pkg]['warning'] + r.group(1)
            
            if self.has_warning and line.startswith("  "): # warning line *seems* to be 2space-indented
                watch[self.pkg]['warning'] = watch[self.pkg]['warning'] + line
            
            m = re.search("Newer version \((\S+)\) available", line)
            if m and not self.has_warning:
                if m.group(1) > 0: watch[self.pkg]['new'] = m.group(1)
        uscan.close()

        if watch[self.pkg]['new'] > 0:
            # extract url from debian/watch file
            url = ''
            for line in file(self.tmpdir + 'debian/watch', 'r').readlines():
                if line.startswith('#'): continue
                if line.startswith('http:') or line.startswith('ftp') or line.count('.') >= 1: 
                    if debug: print "ORIGINAL LINE: " + line
                    line = line.strip()
                    fields = re.split('\s+', line)
                
                    if os.path.basename(fields[0]).count('.') == 1: # this is a page like download.html
                        url = os.path.dirname(fields[0]) + '/'
                    else: url = fields[0]
                    
                    for field in fields[1:]:
                        if field.count('/') >= 1:
                            if not field.endswith('/'): field = field + '/'
                            if not field.startswith('/'): field = '/' + field
                            url = url + field
                        elif field.count('(') == 1:
                            url = url + field
            
            url = url.replace('\\', '')
            url = url.replace('.*', '')
            url = url.replace('///', '/')
            
            if url.startswith('ftp.'): url = 'ftp://' + url
            elif not url.startswith('http://') and not url.startswith('ftp://'): url = 'http://' + url
            
            watch[self.pkg]['url'] = re.sub('\(.*\)', watch[self.pkg]['new'], url)
            if debug: print "UPSTREAM PAGE: " + watch[self.pkg]['url']
            
        if self.has_warning:
            print "WARNING: " + watch[self.pkg]['warning'].replace('\n', ' ')
        else:
            print "new version %s for package %s" % (watch[self.pkg]['new'], self.pkg)

        os.remove(self.tmpdir + 'debian/watch')
        os.remove(self.tmpdir + 'debian/changelog')
        os.removedirs(self.tmpdir + 'debian')
        os.chdir(curdir)
        sem.release()    



# Read watch file for upstream updates [FG]
watch = {}
if os.path.exists(dir + "/watch.txt"):
    f = open(dir + "/watch.txt")
    while 1:
        line = f.readline()
        if not line: break #eof
        line = line.strip()
        try:
            (package, version) = line.split(' ',2)
            watch[package] = {'version': version, 'new': 0, 'warning': "", 'url': ""}
        except ValueError:
            pass
    f.close()

    f = open(odir + "/sources_done", "r")
    sources = cPickle.load(f)
    for key in sources.keys():
        (package, version, dist) = key.split('_')
        if dist != "unstable" and dist != "experimental": continue
        if not watch.has_key(package): continue
#        print "doing " + package + " " + version
        g = os.popen("/usr/bin/dpkg --compare-versions %s gt %s" % (version, watch[package]['version']))
        if g.close() == None:
            watch[package]['version'] = version
    f.close()

    q = Queue.Queue() # we need a thread-safe queue
    for pkg in watch.keys():
        q.put(pkg)
    
    curdir = os.getcwd()
    sem = threading.Semaphore(num_threads)
    while not q.empty():
        thread = find_update()
        thread.start()

    f = open(odir + "/watch_done", "w")
    cPickle.dump(watch, f, 0)
    f.close()
