#!/bin/sh
#

do_cmd=false;

the_imap=/var/imap

os_ver=`uname -r | cut -d. -f1`

case $TERM in
	#   for the most important terminal types we directly know the sequences
	xterm|xterm*|vt220|vt220*)
		        bold=`awk 'BEGIN { printf("%c%c%c%c", 27, 91, 49, 109); }' </dev/null 2>/dev/null`
		norm=`awk 'BEGIN { printf("%c%c%c", 27, 91, 109); }' </dev/null 2>/dev/null`
		;;
	vt100|vt100*|cygwin)
		bold=`awk 'BEGIN { printf("%c%c%c%c%c%c", 27, 91, 49, 109, 0, 0); }' </dev/null 2>/dev/null`
		norm=`awk 'BEGIN { printf("%c%c%c%c%c", 27, 91, 109, 0, 0); }' </dev/null 2>/dev/null`
		;;
esac

if [ `whoami` != "root" ]; then
cat <<X



$0 must be run as ${bold}root${norm} user.



X
exit
fi

case $os_ver in
	8)
		user_is="cyrusimap"
		;;
	7)
		user_is="cyrus"
		;;
	*)
		echo "$0 only runs in Panther and Tiger"
		exit
		;;
esac

while test $# -gt 0; do
	if test "$1" = "--force" -o "$1" = "-f"; then
		do_cmd=true
	fi
	shift
done

color_1=`echo -en "\e[37;40m"`
color_2=`echo -en "\e[37;41m"`
clear
cat <<X
${color_1}                                                                          
  +--------------------------------------------------------------------+  
  |                                                                    |  
  |                          ${color_2} fix_fatal_db ${color_1}                            |  
  |                                                                    |  
  |                           Version 0.3.4                            |  
  |                                                                    |  
  |     Copyright (c) 2005 Dale R. Walsh <dale@daleenterprise.com>     |  
  |                                                                    |  
  +--------------------------------------------------------------------+  
                                                                          

X
tput sgr0

if test "$do_cmd" != true; then
cat     <<X

USE:
	"${bold}spamctl --force${norm}"
OR:
	"${bold}spamctl -f${norm}"

	to perform the repair.


X

else

cat <<X



${bold}Reconstructing the mail databse.${norm}



X

echo "Stoping mail"
serveradmin stop mail 
if [ -d /var/imap.old ]; then   rm -rf /var/imap.old; fi

echo "Moving database: ${the_imap} -> ${the_imap}.old"
mv /var/imap /var/imap.old 

echo "Making new database: -> ${the_imap}"
mkdir -p /var/imap 
/usr/bin/cyrus/tools/mkimap 

echo "Fixing owner: -> ${user_is}:mail"
chown -R ${user_is}:mail /var/imap 

echo "Reconstructing the database: -> ${the_imap}"
sudo -u ${user_is} /usr/bin/cyrus/bin/reconstruct -i 

echo "Starting mail"
serveradmin start mail 

cat <<X



If you see no errors it completed succcessfully.



X
fi

