#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Mail Cyrus
#  helper script: sets quota information for a given user
#
# Copyright 2004-2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

adminuser=0
import os, string, pwd, grp, sys, univention_baseconfig, ldap, tempfile, posix, subprocess, time
import univention.uldap
from pexpect import *

baseConfig = univention_baseconfig.baseConfig()
baseConfig.load()


cyrus_user='cyrus'
hostname='localhost'

if posix.environ.has_key('USER'):
	user_name=posix.environ['USER']
	if baseConfig.get('mail/cyrus/imap/quotainterval') and baseConfig['mail/cyrus/imap/quotainterval'] != "0":
		if os.path.isfile('/var/cache/cyrusquota%s' % user_name):
			currenttime = time.time()
			currenttime = int(currenttime)
			filetime = os.path.getmtime('/var/cache/cyrusquota%s' % user_name)
			difference = currenttime - filetime # in seconds
			minutes = difference/60
			intervall = baseConfig['mail/cyrus/imap/quotainterval']
			if minutes < int(intervall):
				sys.exit(0)
			else:
				os.utime('/var/cache/cyrusquota%s' % user_name, None)
		else:
			subprocess.Popen(['touch /var/cache/cyrusquota%s' % user_name], shell=True)

else:
	sys.exit(1)

if user_name == 'root' or user_name == 'cyrus':
	sys.exit(0)

try:
	l = univention.uldap.getMachineConnection(ldap_master = False, secret_file = "/etc/cyrus-ldap.secret").lo
except ldap.LDAPError, e:
	print 'Cannot connect ldap server: %s' % e
	sys.exit(1)

serverDN = baseConfig['ldap/base']

searchScope = ldap.SCOPE_SUBTREE
searchFilter = "(&(uid=%s)(objectClass=univentionMail))" % user_name
retrieve_attributes = ['mailPrimaryAddress']


try:
	ldap_result = l.search_s(serverDN, searchScope, searchFilter, retrieve_attributes)
	for (dn, attr) in ldap_result:
		user_dn = dn
		mail = attr['mailPrimaryAddress'][0]

except ldap.LDAPError, e:
	sys.exit()
l.unbind()

univentionMQ='0'

mail=mail.strip()
domainpart=mail.split('@')[1]
userpart=mail.split('@')[0].replace( '.', '^' )

if os.path.exists('/var/spool/cyrus/sieve/domain/%s/%s/%s/%s' % (domainpart[0], domainpart, userpart[0], userpart)):

	tempfile=tempfile.mktemp()

	result=os.system("univention_policy_result -D '%s' -y /etc/cyrus-ldap.secret -s '%s' >> '%s'" %  (baseConfig.get('ldap/hostdn'), user_dn, tempfile))

	if result != 0:
		print 'failed to execute univention_policy_result'
		sys.exit(result)

	file=open(tempfile, 'r')

	univentionMQ='0'
	for line in file.readlines():
		line=line.strip(' ').strip('\n')
		if line.startswith('univentionMailQuotaMB='):
			univentionMQ=line.replace('univentionMailQuotaMB=', '').strip('" ')
			univentionMQ=univentionMQ + "000"

	file.close()
	os.remove(tempfile)

else:
	pass

user_name=user_name.strip()

if univentionMQ != '0':
	password=open('/etc/cyrus.secret').read()
	if password[-1] == '\n':
		password=password[0:-1]

	if baseConfig.has_key('mail/cyrus/murder/backend/hostname') and baseConfig['mail/cyrus/murder/backend/hostname']:
		hostname = baseConfig['mail/cyrus/murder/backend/hostname']

	child = spawn('/usr/bin/cyradm -u %s %s' % (cyrus_user, hostname))
	i=0
	while not i == 3:
		i = child.expect(['Password:', '>', 'cyradm: cannot connect to server', EOF], timeout=60)
		if i == 0:
			child.sendline(password)
		elif i == 1:
			child.sendline('setquota user/%s %s' % (mail, univentionMQ))
			child.sendline('disc')
			child.sendline('exit')
		elif i == 2:
			sys.exit(1)
else: #unset quota
	password=open('/etc/cyrus.secret').read()
	if password[-1] == '\n':
		password=password[0:-1]

	if baseConfig.has_key('mail/cyrus/murder/backend/hostname') and baseConfig['mail/cyrus/murder/backend/hostname']:
		hostname = baseConfig['mail/cyrus/murder/backend/hostname']

	child = spawn('/usr/bin/cyradm -u %s %s' % (cyrus_user, hostname))
	i=0
	while not i == 3:
		i = child.expect(['Password:', '>', 'cyradm: cannot connect to server', EOF], timeout=60)
		if i == 0:
			child.sendline(password)
		elif i == 1:
			child.sendline('setquota user/%s none' % mail)
			child.sendline('disc')
			child.sendline('exit')
		elif i == 2:
			sys.exit(1)
