#!/usr/bin/python2.4
# -*- coding: iso-8859-1 -*-
#
# copyright (c) 2004-2007 praKsys
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# $Id: ttsmailbot.py,v 1.14 2004/07/26 04:53:33 gpernot Exp $

import email, sys, smtplib, string, re
import os, ConfigParser, random

from logging import basicConfig, debug, DEBUG

from unac import unacString

from email.MIMEText import MIMEText
from email.Utils import quote
from email.Header import decode_header

def sendNotifications(config, params):
	"""Send back a notice message to sender"""

	msg = MIMEText( config.notification_template % params )
	msg['Subject'] = 'Tiny instance created'
	msg['From'] = 'noreply@tiny-erp.fr'
	msg['To'] = params['email']
	
	s = smtplib.SMTP(config.smtp)
	s.sendmail('tinybot@front.praksys.org', [params['email'], config.email], msg.as_string())
	s.close()

def createTinyInstance(config, params):
	"""Creates tinyerp instance and notify admins and owner"""
	pass

		
def parseMail(config, mail) :
	"""Parse creation request email"""

	sender = mail.get('From')
	date = mail.get('Date')

	# reject mails originating from MAILER-DAEMON
	m = re.search(r'MAILER-DAEMON', sender)
	if m != None :
		debug ('MAILER-DAEMON in sender')
		sys.exit(0)

	subject = ''
	for s in decode_header(mail.get('Subject')) :
		subject = subject + " " + s[0]
	subject = subject.strip()

	# get message from mail
	message = ''
	for part in mail.walk() :
		if part.get_content_maintype() == 'multipart':
			continue
		m = part.get_payload(decode=1)
		if m != None :
			message = message + "\n" + m

	m = re.search(r'###REQUEST BEGIN(.*)###REQUEST END', message, re.DOTALL)

	if not m.group(1):
		debug('Invalid email format')
		raise Exception, "Invalid email format"

	params = {}
	
	debug( 'will exec : %s' % m.group(1) )
	
	exec m.group(1) in params

	return params

			
class PBOConfig(object):
	def __init__(self) :
		config = ConfigParser.ConfigParser()
		config.read(['/etc/tiny-asp/tiny-asp.cfg',
			     'etc/tiny-asp.cfg' ])

		for item in config.items('tinyerp'):
			self.__dict__[item[0]] = item[1]
		
		for mandatory in ['smtp', 'email', 'notification_template']:
			if not self.__dict__.has_key(mandatory):
				debug('missing %s parameter' % mandatory)

		template = open(config.get('tinyerp', 'notification_template'))
		self.notification_template = template.read()
		template.close()

def randomPassword():
	random.seed()
	return str( random.randrange(10000, 99999, 1) )

def databaseName(params):
	database = unacString(params['company'].strip().lower()).decode('utf-8')
	database = re.sub('[\(\),\s\'\.-]', '', database).strip()
	
	return database

def main():
	"""Take a mail as input and create tiny instance with given params"""
	
	config = PBOConfig()
	mail_content = email.message_from_string( sys.stdin.read() )
	params = parseMail(config, mail_content)
	params['password'] = randomPassword()
	params['database'] = databaseName(params)
	createTinyInstance(config, params)
	sendNotifications(config, params)
	

if __name__ == "__main__":
	basicConfig(level=DEBUG, filename='/tmp/tiny-asp.log')

	# never fails
	try:
		main()
	except Exception, error:
		debug('Exception catched: %s' % error)
