#!/usr/bin/env python2
# Author: Rafal Zawadzki <bluszcz@Jabberpl.org>
# Under the terms of:
# GNU GENERAL PUBLIC LICENSE
# Version 2, June 1991
# http://www.gnu.org/copyleft/gpl.html
# This tools vacuuming queue for jabberd2 (mysql storage).
import sys, time, re

def printdebug(logtxt):
	print time.strftime("[%H:%M] ")+str(logtxt)
try: 
	import MySQLdb
except:
	printdebug("""python-mysqldb not found... you should check http://sourceforge.net/projects/mysql-python
	or apt-get install python-mysqldb (debian like unix)""")
	sys.exit(0)

datepattern = re.compile(r'.*stamp=\'([0-9]{8,8})T.*')

### DEFINE DATABASE CONNECTION
dbhost="localhost"
dbuser="jabberd2"
database="jabberd2"
dbpassword="12345aa"

### MINIMAL COUNTS OF QUEUE MESSAGES TO VACUUM
queuelimit=10000

### DEFINE type of messages and their lifetime
### FOR EXAMPLE: below messages of type headlines will be deleted
### IF THE ARE OLDER THAN 1 day
### {"name":        "headline",     "days":"1"}

vacuumlist =	[
			{"name":	"headline",	"days":"1"},
			{"name":	"error",	"days":"20"},
			{"name":	"ALL",		"days":"31"},
		]	


def printdate(dat):
	datetime=time.localtime(dat)
	return time.strftime("%Y%m%d",time.localtime(dat))
		


class VacuumDatabase:
    def __init__(self,stream,dbhost, dbuser, database, dbpassword):
        printdebug("DB connecting...")
        self.stream=stream
	try:
	        self.connection=MySQLdb.connect(user=dbuser,passwd=dbpassword,db=database,host=dbhost)
	        self.connection.threadsafety=1
	        self.dbcursor=self.connection.cursor()
        	printdebug("DB connect success!")
			
	except:
        	printdebug("DB connect failed, exit!!!")
		sys.exit(0)
		
		

    def countqueue(self):
    	querytxt="SELECT COUNT(*) FROM queue;"
	self.dbcursor.execute(querytxt)
	return self.dbcursor.fetchall()[0][0]

    def deletequeue(self,name,date01):
    	delcounter=0
    	if not name=="ALL":
	    	querytxt="SELECT * FROM queue WHERE xml LIKE '%type=\\'"+name+"\\'%'; "
	else:
		querytxt="SELECT * FROM queue; "
    	printdebug(querytxt)
	self.dbcursor.execute(querytxt)
	for queryresult in self.dbcursor.fetchall():
		wynik = int((re.findall(datepattern,queryresult[2]))[0])
		#printdebug(":: "+str(wynik)+" :: "+str(date01))
		if int(wynik)<=int(date01):
			querytxt="DELETE FROM queue WHERE `object-sequence` ='"+str(queryresult[1])+"';"
			self.dbcursor.execute(querytxt)
			delcounter+=1
			#printdebug("Delete message ID: "+str(queryresult[1])+" with date "+str(wynik))
			#printdebug(querytxt)
	if delcounter>=1:
		printdebug("Deleted summary "+str(delcounter)+" message, type: "+name)
	if delcounter==0:
		printdebug("No message type: "+name+" find to remove")
		


cleanup=VacuumDatabase(None,dbhost, dbuser, database, dbpassword)
queuesize=cleanup.countqueue()
if queuesize>=queuelimit or queuelimit==0:
	printdebug("Queue size (" +str(queuesize) + ") bigger than queue limit ("+str(queuelimit)+"), start vacuum.")
	
else:
	printdebug("Queue size (" +str(queuesize) + ") smaller than queue limit ("+str(queuelimit)+"), exiting!")
	sys.exit(0)

queuestartsize=int(queuesize)
queueendsize=0

for i in vacuumlist:
	daycount=int(i["days"])
	datetoday=time.strftime("%s",time.localtime())
	dateold=int(datetoday)-(daycount*86400)
	date00=(printdate(int(datetoday)))
	date01=(printdate(int(dateold)))
	#print date00
	#print date01
	printdebug("Deleting messages type '"+i["name"]+"' and older than "+str(date01))
	cleanup.deletequeue(i["name"],date01)
	
queueendsize=cleanup.countqueue()
printdebug("I've started with "+str(queuestartsize)+", finished with: "+str(queueendsize)+", summary "+str(queuestartsize-queueendsize)+" deleted")
