#! /bin/sh
#
# Maildir2IMAPdir (v0.2) - convert Maildir++ depots to IMAPdir depots
# Copyright (C) 2004  Henry Baragar mailto:Henry.Baragar@Instantiated.ca
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed 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 General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# WARNING:
#	All activity on the Maildir must be stopped before running this
#	script.  MAIL MAY BE LOST if you do not.  This includes both MTA's
#	(e.g. qmail, postfix) and MUA's (e.g. bincimap).
#
# WARNING:
#	There is no attempt to convert .qmail* files, .mailfilter or any 
# 	other files that affect mail delivery:  that is YOUR RESPONSIBILITY.
#
# This script converts a Maildir++ to an IMAPdir, using brute force
# and ignorance.  It is invoked as follows:
#	Maildir2IMAPdir.sh Maildir IMAPdir
# If it completes successfully, you will see two new directories:
#	IMAPdir		- the new IMAPdir
#	Maildir.bak	- the original Maildir
# Since Maildir has been removed, delivery instructions to Maildir will fail.
# So, make sure you convert all your .qmail, etc. files and the same time.
# And yes, your mail is now taking up twice as much space, which can be 
# recovered by removing Maildir.bak (after you have convinced yourself that
# the migration was a success).
# 
# See Maildir2IMAPdir.pl for a more sophisticated conversion utilility.
#

set -e
USAGE="Usage: $0 [Maildir [IMAPdir]]"

#
# Get the input paramters
#
if echo " $*" | grep -q " -" 
then
    echo $USAGE
    exit 1
fi
if [ $# -gt 2 ]
then
    echo $USAGE
    exit 1
fi
Maildir=${1-Maildir}
IMAPdir=${2-IMAPdir}

#
# Copy the mail from the one depot to the other and rename the folders to
# adhere to the IMAPdir naming convention
#
cp -Rp "$Maildir" "$IMAPdir/"
OPWD="`pwd`"
cd $IMAPdir
mkdir .INBOX-$$
mv * .INBOX-$$
mv .INBOX-$$ INBOX
set -- `ls -ld` && chown $3:$4 INBOX
chmod go= INBOX
for i in .* 
do
    mv "$i" "INBOX$i"
done

# Preserve the bincimaped-subscribed file (if there is one)
mv INBOX.bincimap-subscribed .bincimap-subscribed  2>/dev/null || :

#
# We have success, so disable the old Maildir
#
cd "$OPWD"
mv "$Maildir" "$Maildir.bak"
