#!/usr/bin/python

import sys
import cgi
import popen2




def es(s):
	q=s.replace('\'',r'\'' )
	return q

"""
To send the SQL INSERT statement to the database, define
the db_connect string to contain what you would normally
use on the command line.  Make sure you fully specify the 
path of the require binary as there's no guarantee that the
shell path will be available during the execution of this
script
"""

db_connect='/usr/local/pgsql/bin/psql -U user xamime'
#db_connect='/usr/bin/mysql -s --user=user xamime';
#db_connect='/usr/local/bin/sqlite /usr/local/xamime/xamime_sqlite.db';

r,w = popen2.popen2(db_connect)

foo = sys.stdin.read()
data = cgi.parse_qs(foo)
db_table = 'emails'


sql = "INSERT into %s (utstamp,timestamp,eid,global_status,block_status,mailpack_size,hitcomment,acl_key,acl_name,acl_comment,sender,receiver,retained_path,source_ip,mta_result) values ( %s, '%s','%s', %s, %d, %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s',%s );" % (
			db_table
			,data['utstamp'][0]
			,es(data['timestamp'][0])
			,es(data['eid'][0])
			,es(data['global_status'][0])
			,ord(data['block_status'][0][0])
			,es(data['mailpack_size'][0])
			,es(data['block_comment'][0])
			,es(data['acl_key'][0])
			,es(data['acl_name'][0])
			,es(data['acl_comment'][0])
			,es(data['sender'][0])
			,es(data['receiver'][0])
			,es(data['retained_path'][0])
			,es(data['source_ip'][0])
			,es(data['mta_result'][0])
			)

w.write(sql)

