#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Mail Cyrus Murder
#  mailbox move script
#
# Copyright (C) 2008-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/>.

import sys, os, string, getopt, univention.config_registry
from pexpect import *

def cyrescape(address):
	address=address.replace("@","\@")
	address=address.replace(".","\^")
	return address.strip()

def usage():
	print 'usage: %s [-o] <folder> <new backend fqdn>' % sys.argv[0]
	sys.exit(1)


try:
	opts, args = getopt.gnu_getopt(sys.argv, 'oh', ['help'])
except getopt.GetoptError, err:
	print str(err)
	usage()
# arguments
if len(args) == 3:
	mbox=args[1].lower()
	localbackend=args[2].lower()
else:
	usage()
# options
for o, a in opts:
	if o in ("-h", "--help"):
		usage()
	else:
		assert False, "unhandled option"

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

isMurder = False
murders = registry.get('mail/cyrus/murder/servers', "")
fqdn = '%s.%s' % (registry['hostname'], registry['domainname'])

if registry['hostname'] + "$" in murders.split(" "):
	isMurder = True

if not isMurder:
	print >> sys.stderr, "this host is not a cyrus murder server"
	sys.exit(1)

cyrus_user='cyrus'

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

child = spawn('/usr/bin/cyradm -u %s %s' % (cyrus_user, fqdn))
i=0
c=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:
		if c==0:
			print 'renamemailbox user/%s user/%s %s' % (mbox, mbox, localbackend)
			child.sendline( 'rename user/%s user/%s %s' % (mbox, mbox, localbackend))
			c+=1
		elif c==1:
			if child.before.find('renamemailbox: ') != -1:
				print child.before.split('\n')[1]
				sys.exit(1)
			child.sendline('disc')
			c+=1
		elif c==2:
			child.sendline('exit')
	elif i == 2:
		sys.exit(1)
