#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Mail Cyrus
#  helper script: deletes a mailbox
#
# Copyright 2010-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.config_registry
import getopt, glob
from subprocess import *

def cyrescape(address):	# only necessary for filesystem level operations
	address=address.replace("@","\@")
	address=address.replace(".","\^")
	return address.strip()

def usage():
	print 'usage: %s [-v] [--user, --shared] <mailbox>' % sys.argv[0].split('/')[-1]
	sys.exit(1)

try:
	opts, args = getopt.getopt(sys.argv[1:], "v", ["user", "shared"])
except getopt.GetoptError, err:
	# print help information and exit:
	print str(err) # will print something like "option -a not recognized"
	usage()
partition = None
prefix = 'shared'	# default
verbose = 0
for key, val in opts:
	if key == "-v":
		verbose += 1
	elif key in ("--partition"):
		partition = val
	elif key in ("--shared"):
		prefix = 'shared'
	elif key in ("--user"):
		prefix = 'user'
	else:
		assert False, "unhandled option"

if not prefix:
	print 'prefix must not be empty'
	sys.exit(1)

if len(args) == 1:
	dst=args[0].lower().strip()
else:
	usage()

configRegistry = univention.config_registry.ConfigRegistry()
configRegistry.load()

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

cyrus_user='cyrus'
serverhost='localhost'

if configRegistry.get('mail/cyrus/murder/backend/hostname'):
	serverhost = configRegistry['mail/cyrus/murder/backend/hostname']
elif configRegistry.get('mail/cyrus/murder/master'):
	serverhost = '%s.%s' % (configRegistry['hostname'], configRegistry['domainname'])

if partition and partition != 'default' and not configRegistry.get('mail/cyrus/murder/servers'):
	print >> sys.stderr, "this host is not a cyrus murder frontend"
	sys.exit(1)

cmd_list=[]
cmd_list.append('sam %s/%s cyrus cd' % (prefix, dst))
cmd_list.append('dm %s/%s' % (prefix, dst))
cmd_list.append('disc')
cmd_list.append('exit')
script='\n'.join(cmd_list)

if verbose > 1:
	print "/usr/bin/cyradm", "-u", cyrus_user, "--password=%s" % password, serverhost
default_env={'TERM': 'vt100', 'COLUMNS': '80', 'LINES': '24'}
default_env.update(os.environ)
p = Popen(["/usr/bin/cyradm", "-u", cyrus_user , "--password=%s" % password, serverhost], stdin=PIPE, stdout=PIPE, stderr=PIPE, env=default_env)
(stdout, stderr)=p.communicate(script)
if verbose:
	print stdout
if stderr:
	print stderr
	sys.exit(1)

if prefix == 'user':
	# delete sieve directory
	dst_domainpart=dst.split('@')[1]
	dst_userpart=dst.split('@')[0]
	dst_userpart_modified=dst_userpart.replace(".", "^")
	dst_sieve_path='/var/spool/cyrus/sieve/domain/%s/%s/%s/%s' % (dst_domainpart[0], dst_domainpart, dst_userpart_modified[0], dst_userpart_modified)

	if os.path.exists(dst_sieve_path):
		r = glob.glob('%s/*' % dst_sieve_path)
		for f in r: # probably unnecessary, as cyrus deletes the scripts
	 		os.unlink(f)
		os.rmdir(dst_sieve_path)
