#!/usr/bin/python2.4
import sys
import os
from urllib import urlopen
from subprocess import Popen

sites = [('techAssault','http://techassault.de/portal/de/index.php?sec=news', 3)]


"""HTML Diff: http://www.aaronsw.com/2002/diff
Rough code, badly documented. Send me comments and patches."""
import difflib, string

def isTag(x): return x[0] == "<" and x[-1] == ">"

def textDiff(a, b):
	"""Takes in strings a and b and returns a human-readable HTML diff."""

	out = []
	a, b = html2list(a), html2list(b)
	s = difflib.SequenceMatcher(isTag, a, b)
	for e in s.get_opcodes():
		if e[0] == "replace":
			# @@ need to do something more complicated here
			# call textDiff but not for html, but for some html... ugh
			# gonna cop-out for now
			out.append('<del class="diff modified">'+''.join(a[e[1]:e[2]]) + '</del><ins class="diff modified">'+''.join(b[e[3]:e[4]])+"</ins>")
		elif e[0] == "delete":
			out.append('<del class="diff">'+ ''.join(a[e[1]:e[2]]) + "</del>")
		elif e[0] == "insert":
			out.append('<ins class="diff">'+''.join(b[e[3]:e[4]]) + "</ins>")
		elif e[0] == "equal":
			out.append(''.join(b[e[3]:e[4]]))
		else: 
			raise "Um, something's broken. I didn't expect a '" + `e[0]` + "'."
	return ''.join(out)

def html2list(x, b=0):
	mode = 'char'
	cur = ''
	out = []
	for c in x:
		if mode == 'tag':
			if c == '>': 
				if b: cur += ']'
				else: cur += c
				out.append(cur); cur = ''; mode = 'char'
			else: cur += c
		elif mode == 'char':
			if c == '<': 
				out.append(cur)
				if b: cur = '['
				else: cur = c
				mode = 'tag'
			elif c in string.whitespace: out.append(cur+c); cur = ''
			else: cur += c
	out.append(cur)
	return filter(lambda x: x is not '', out)

def view():
    global sites
    for i in sites:
        if os.path.exists('/var/local/oppu/%s.html' % i[0]):
            show =open('/var/local/oppu/%s.html' %i[0], 'r').read().split('\n', 1)

            if int(show[0]) + 1 > i[2]:
                # save new version
                page = urlopen(i[1]).read()
                open('/var/local/oppu/%s' % i[0], 'w').write(page)
                # delete .show
                os.unlink('/var/local/oppu/%s.html' %i[0])
            else:
                show[0] = str( int(show[0]) + 1 )
                open('/var/local/oppu/%s.html' %i[0], 'w').write('\n'.join(show))
            print 'changes in: ' + i[0]
            do = raw_input('[Firefox, Leave]')
            if do.lower() in ('firefox', 'f'):
                Popen(('firefox', '/var/local/oppu/%s.html' %i[0]))

def check():
    global sites, show
    
    for i in sites:
        page = urlopen(i[1]).read()

        # exists a saved version of this page already?
        if os.path.exists('/var/local/oppu/%s' % i[0]):
            old = open('/var/local/oppu/%s' %i[0], 'r').read()
            if old != page:
                show = open('/var/local/oppu/%s.html'%i[0], 'w')
                show.write('0\n'+textDiff(page, old))
                
                # change permission - i didnt find a nicer / pythonic way
                Popen(('/bin/chmod','777', '/var/local/oppu/%s.html'%i[0]))
                Popen(('/bin/chmod','777', '/var/local/oppu/%s'%i[0]))
        else:
            open('/var/local/oppu/%s' % i[0], 'w').write(page)

if 'check' in sys.argv:
    check()

if 'view' in sys.argv:
    view()
