#!/usr/bin/env python

import urllib
import string
import smtplib
import rxb 
import re 
import sys
import time
import thread
import socket
import resource


from htmllib import *
from cStringIO import StringIO

G_DEBUG = 1
G_FROM = '"The gnut killer" <honey@7thguard.net>'
G_TO = '" A humble 7g reader" <kowalski@kowalski.com>'
G_LASTONE = 0
G_MINUTE = 60
#G_TAIMAUT = G_MINUTE * 20
G_TAIMAUT = 1

from html2text import HTML2Text

def html2text(s):
    parser = HTML2Text()
    parser.feed(s)
    parser.close()
    return parser.result


def sendmesycz(mesycz):
    server = smtplib.SMTP('localhost')
    server.sendmail(G_FROM,G_TO,html2text(mesycz))
    server.quit()
    if G_DEBUG == 1: print "mail sent"

def getpejcz(urlik):
    a=urllib.urlopen("http://7thguard.net/news.php?id=" + urlik)
    if G_DEBUG == 1: print "getting news no ", urlik
    b=a.read()
    for i in range (len(b)):
	pat = rxb.label.spam(rxb.exactly("<!-- tabelka z treścią -->"))
	pat.search(b)
	d = pat.after
    return d

def get7list():
    a=urllib.urlopen("http://7thguard.net")
    if G_DEBUG == 1: print "index opened"
    b=a.read()
    c=string.split(b,'<div class="head"')
    numberlist = []
    for i in range (len(c)):
	pat = rxb.label.spam(rxb.exactly("id="))
	pat.search(c[i])
	d = pat.after
	pat2 = rxb.label.spam(rxb.some(rxb.digit))
	pat2.search(pat.after)
	numberlist.append(pat2.found)
    return numberlist

def poczontek():
    global G_LASTONE
    d = get7list()
    d.reverse()
    for i in d[0:(len(d)-1)]:
	l = getpejcz(i)
        sendmesycz(l)
    G_LASTONE = eval(i)

	
def sprawdz7g():
    global G_LASTONE
    x = 0
    while x == 0:
	time.sleep(G_TAIMAUT)
	d = get7list()
	d.reverse()
	print d
	for i in d[0:(len(d)-1)]:
	    if eval(i) > G_LASTONE:
		print "found a new news:", i
		l = getpejcz(str(i))
		sendmesycz(l)
		G_LASTONE = eval(i)
	    


def gimme_res():
    m = 'HTTP/1.1 200 OK\nContent-Type: text/html\n\n<html><head><title>Guardian status</title></head><body bgcolor="#FFFFFF"><center>'
    reso = resource.getrusage(0)
    n = "Time in user mode: " + str(reso[0]) + "<br>" + \
    "Time in system mode: " + str(reso[1]) + "<br>" + \
    "Maximum resident set size: " + str(reso[2]) + "<br>" + \
    "Shared memory size: " + str(reso[3]) + "<br>" + \
    "Unshared memory size: " + str(reso[4]) + "<br>" + \
    "Unshared stack size: " + str(reso[5]) + "<br>" + \
    "Page faults not requiring I/O: " + str(reso[6]) + "<br>" + \
    "Page faults requiring I/O: " + str(reso[7]) + "<br>" + \
    "Number of swap outs: " + str(reso[8]) + "<br>" + \
    "Block input operations: " + str(reso[9]) + "<br>" + \
    "Block output operations: " + str(reso[10]) + "<br>" + \
    "Messages sent: " + str(reso[11]) + "<br>" + \
    "Messages received: " + str(reso[12]) + "<br>" + \
    "Signals received: " + str(reso[13]) + "<br>" + \
    "Voluntary context switches: " + str(reso[14]) + "<br>" + \
    "Involuntary context switches: " + str(reso[15]) + "<br> </center>" 
    return m + n

def nasluchuj(n):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind(('localhost',8081))
    s.listen(2)
    while 1:
	conn,addr = s.accept()
    	time.sleep(0.1)
        data = conn.recv(1024)
        if not data: break
        conn.send(gimme_res())
	conn.close()


if (G_TO == '"A humble 7g reader" <kowalski@kowalski.com>'):
    print "You have to set G_TO at least..."
    print "Poor Kowalski hates spam as much as you do..."
    sys.exit()

thread.start_new_thread(nasluchuj,('',))
poczontek()
sprawdz7g()