#!/bin/sh -
# This script repais mailboxes.db by perfoming maildirs lookup at cyrus partition and create a file in
# cyrus databases text dump format.
# Then it delete corrupted mailboxes.db file and makes a new one from a text dump.  
#
# ##################################################################
# !!! It will work only if you have one default cyrus partition. !!!
# ##################################################################
#
# No warranties - use at your own risc. Tested on Cyrus 2.3.7 at FreeBSD 6.1
# CYRUSER: user owns cyrus config directory. Please change it if in your system cyrus own another user. 

CYRUSER=cyrus

usage(){
	printf "\nUsage:\nsh $0 path_to_imapd.conf\n\n"
}

if  [ `id -u` -ne 0 ] ; then printf "\nThis script must be done as root\n\n" && usage && exit 3 ; fi 

if [ -z "${1}" -o ! -r ${1} ] 
then
	usage
	printf "\tpath_to_imapd.conf is empty or file cannot be read
	Please specify a full path to imapd.conf\n"
	exit 3
fi

IMAPDCONF=${1}
exit 999

# Define some variables from imapd.conf.
CONFIGDIR=`grep configdirectory ${IMAPDCONF} | awk '{print $2}'`
if [ -z "${CONFIGDIR}" ] ; then printf "CONFIGDIR cannot be readen from ${IMAPDCONF}\n" && exit 3 ; fi
PARTITION=`grep partition-default ${IMAPDCONF} | awk '{print $2}'`
if [ -z "${PARTITION}" ] ; then printf "PARTITION cannot be readen from ${IMAPDCONF}\n" && exit 3 ; fi
TEXTDB=/tmp/mailboxes.txt
CTL_MBX=/usr/local/cyrus/bin/ctl_mboxlist

rm -f ${TEXTDB}

# Finding all user maildirs
find ${PARTITION}/user -type d -mindepth 1 | awk -F/user/ '{print $2}' | sed "s/\//\./g" | \
while read userdir 
do
	# Striping username
	username=`echo ${userdir} | awk -F. '{print $1}'`
	# Printing output to a cyrus mailboxes text format
	printf "user.${userdir}\t0 default\t${username}\tlrswipkxtea\t\n" >> ${TEXTDB}
done

# Deleting old mailboxes.db
rm -f ${CONFIGDIR}/mailboxes.db
# Importing new mailboxes.db from a TEXTDB
su ${CYRUSER} -c "${CTL_MBX} -u < ${TEXTDB}" && exit 0