#!/usr/bin/python2.2

# Make sure tabs expand to 8 spaces in vim
# vim: expandtab

# Copyright 2002 Raphaël Hertzog
# This file is distributed under the terms of the General Public License
# version 2 or (at your option) any later version.

import os.path, rfc822, sys, string, re, cPickle
from xml.dom import implementation, ext

from config import dir, odir

def striphtml(input):
    cleared = input.strip()
    # I have to clean it this way first because dependencies are copied raw
    # in update_excuses.html ...
    cleared = cleared.replace(">=", "&gt;=");
    cleared = cleared.replace("<=", "&lt;=");
    cleared = cleared.replace(">>", "&gt;&gt;");
    cleared = cleared.replace("<<", "&lt;&lt;");
    while cleared.find("<") != -1 and cleared.find(">") != -1:
        cleared = cleared[:cleared.find("<")] + cleared[cleared.find(">")+1:]
    return cleared

# Load the list of excuses generated last time
old_done = {}
new_done = {}
if os.path.exists(odir + "/excuses_done"):
    f = open(odir + "/excuses_done", "r")
    old_done = cPickle.load(f)
    f.close()

f = open(dir + "/update_excuses.html", "r")
# Ignore everything until first list
while string.find(f.readline(), "<ul>") == -1: 
    pass

top = 1
package = ""
hash = ""
doc = None
while 1:
    line = f.readline()
    if not line: break #eof
    if line.find("</ul>") != -1: 
        top = 1
        if os.path.exists("%s/%s/%s" % (odir, hash, package)):
            excf = open("%s/%s/%s/excuse.xml" % (odir, hash, package), "w")
            ext.PrettyPrint(doc, excf, "iso-8859-1")
            excf.close()
            new_done[package] = 1
        continue
    if line.find("<ul>") != -1: 
        top = 0
        continue
    # The rest depends of the state
    if top:
        words = re.split("[><() ]", line)
        package = words[6]
        hash = package[0]
        if package[0:3] == "lib":
            hash = package[0:4] 
        # Create the XML Document
        doc = implementation.createDocument(None, "excuse", None)
        main_elt = doc.documentElement
        top = 0
    else:
        for subline in line.split("<li>"):
            if not subline: continue
            subline = subline.strip()
            if subline.find("Maintainer:") != -1: continue
            elif subline.find("Too young,") != -1:
                words = subline.split()
                main_elt.setAttribute("age", words[3])
                main_elt.setAttribute("limit", words[5])
                main_elt.setAttribute("progress", "%d" % (100.0 * string.atoi(words[3]) / string.atoi(words[5])))
                subline = striphtml(subline)
                sub_elt = doc.createElement("item")
                sub_elt.appendChild(doc.createTextNode(subline))
                main_elt.appendChild(sub_elt) 

            elif subline.find("days old (needed") != -1:
                words = subline.split()
                main_elt.setAttribute("age", words[0])
                main_elt.setAttribute("limit", words[4])
                main_elt.setAttribute("problematic", "yes")
                subline = striphtml(subline)
                sub_elt = doc.createElement("item")
                sub_elt.appendChild(doc.createTextNode(subline))
                main_elt.appendChild(sub_elt) 
            else:
                sub_elt = doc.createElement("item")
                start = subline.find('href="http://')
                if start != -1:
                    url = subline[start+6:subline.find('"',start+6)]
                    sub_elt.setAttribute("url", url)
                start = subline.find('href="#')
                if start != -1:
                    url = subline[start+7:subline.find('"',start+7)]
                    sub_elt.setAttribute("url", "http://packages.qa.debian.org/" + url)
                subline = striphtml(subline)
                sub_elt.appendChild(doc.createTextNode(subline))
                main_elt.appendChild(sub_elt)

f.close()

# Store the new list
f = open(odir + "/excuses_done", "w")
cPickle.dump(new_done, f, 0)
f.close()

# Find excuses generated last time and not this time
# and remove them
for p in old_done.keys():
    if not new_done.has_key(p):
        hash = p[0]
        if p[0:3] == "lib":
            hash = p[0:4] 
        filename = "%s/%s/%s/excuse.xml" % (odir, hash, p)
        filenamerebuild = "%s/%s/%s/force-rebuild" % (odir, hash, p)
        if os.path.exists(filename):
            os.unlink(filename)
            f = open(filenamerebuild, "w")
            f.close()

# We're done
