#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Mail Cyrus
#  helper script: renames a mailbox
#
# 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
from pexpect import *
def cyrescape(address):
	address=address.replace("@","\@")
	address=address.replace(".","\^")
	return address.strip()
def usage():
	print 'usage: univention-cyrus-rename-mailbox <SHARED FOLDER OLD> <SHARED FOLDER NEW>'
	sys.exit(1)

import smtplib

from email.MIMEText import MIMEText


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


cyrus_user='cyrus'
hostname='localhost'

if len(sys.argv) == 3 and sys.argv[1]:
	src=sys.argv[1].lower()
	dst=sys.argv[2].lower()
else:
	usage()

src=src.strip()
dst=dst.strip()

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:
		print 'renamemailbox shared/%s shared/%s' % (src, dst)
		child.sendline('renamemailbox shared/%s shared/%s' % (src, dst))
		child.sendline('disc')
		child.sendline('exit')
	elif i == 2:
		sys.exit(1)
