# Script to convert cyrus mailboxes to maildir
# (c) 2004 M.J.London

if [ $# -lt 2 ]; then
	echo "Usage: $0 CyrusBoxPath MailDirPath [User]"
	echo "  CyrusBoxPath is the path to your cyrus mailbox"
	echo "    e.g /var/spool/imap/username"
	echo "  MailDirPath is the path to your Maildir"
	echo "    e.g. /home/username/Maildir"
	echo "  User is a user to chown the Maildir to if you run as root"
	exit 1
fi

CYRPATH=$1
MAILDIRPATH=$2
if [ -n "$3" ]; then
	MDUSER=$3
fi

if [ ! -d $CYRPATH ]; then
	echo $CYRPATH: Not a directory
	exit 1
fi

if [ ! -d $MAILDIRPATH ]; then
	DIRNAME=$(dirname $MAILDIRPATH)
	if [ ! -d $DIRNAME ]; then
		echo $DIRNAME: Not a directory
		exit 1
	fi
	maildirmake $MAILDIRPATH
	mdexit=$?
	if [ $mdexit -ne 0 ]; then
		echo maildirmake exited with $mdexit
		exit $mdexit
	fi
fi

if [ ! -d $MAILDIRPATH/new ]; then
	echo $MAILDIRPATH/new: Not a direcoty
	echo $MAILDIRPATH is not a MailDir
	exit 1
fi

convertcyr() {
	CYRBOX=$1
	MAILDIR=$2

	MSGPREFIX=$(date +%s).$(hostname)
	echo Using MailDir file prefix: $MSGPREFIX

	ls $CYRBOX/*. >/dev/null 2>/dev/null || return

	for cyrmsg in $CYRBOX/*.; do 
		msgid=$(basename $cyrmsg | sed 's/\.//g')
		cp -v $cyrmsg $MAILDIR/new/$MSGPREFIX.$msgid
	done
}

echo Processing INBOX...
convertcyr $CYRPATH $MAILDIRPATH

for cyrfolder in $(find $CYRPATH -type d -maxdepth 1 -print | grep -v "^$CYRPATH\$"); do
	folder=$(basename $cyrfolder)
	echo Processing $folder...
	if [ ! -d $MAILDIRPATH/.$folder ]; then
		maildirmake -f $folder $MAILDIRPATH
	fi
	convertcyr $cyrfolder $MAILDIRPATH/.$folder
done

if [ -n "$MDUSER" ]; then
	chown -R $MDUSER $MAILDIRPATH
fi
