#!/bin/sh
#
# /usr/local/sbin/adduser.local
# Copyright 2005-2006 Jonas Smedegaard <dr@jones.dk>
#
# $Id: localmb2md,v 1.10 2006-08-20 20:36:04 jonas Exp $
#
# Convert user account from mailboxes below /var/mail/ and ~/mail/ to
# maildirs below ~/Maildir/ .
#
# If from a different account, execute it like this:
#
#     su -s /bin/sh -c localmb2md - <user>
#
# FIXME: Make sure no MUAs or pop/imap daemons are running
# TODO: Add --help (and perhaps --force) options
#

set -e

# Unset these if the MDA delivers to Maildir without being told explicitly
mkprocmailrc="yes"

# Change this to ".subscriptions" if using pre-1.xx Dovecot
subscriptions="subscriptions"

if [ -e /etc/local/mb2md.conf ]; then
	. /etc/local/mb2md.conf
fi

helpers="/usr/bin/mb2md /usr/bin/mail-lock /usr/bin/mail-touchlock /usr/bin/mail-unlock"
if [ -n "$mkprocmailrc" ]; then
	helpers="$helpers /usr/bin/procmail"
fi

# Make sure all required tools are available
for prg in $helpers; do
	if [ ! -x "$prg" ]; then
		echo "ERROR: $prg not installed!"
		exit 1
	fi
done

# Bail out if custom procmailrc is in the way
if [ -n "$mkprocmailrc" ] && [ -f ~/.procmailrc ]; then
	if ! grep -q -x 'DEFAULT=\$HOME/Maildir/' ~/.procmailrc; then
		cat <<EOF
ERROR: non-Maildir-aware ~/.procmailrc exists already.
    Please edit manually to include the following line:

        DEFAULT=\$HOME/Maildir/

    Make sure other rules use Maildirs too, if needed.
EOF
		exit 1
	else
		mkprocmailrc=""
	fi
fi

init_inbox() {
	mkdir -p ~/Maildir/cur ~/Maildir/new ~/Maildir/tmp
	chmod -R u=rw,go=,u+X ~/Maildir
}

promote_inbox() {
	if [ -n "$mkprocmailrc" ]; then
		echo 'DEFAULT=$HOME/Maildir/' > ~/.procmailrc
	fi
	mkprocmailrc=''
}

# Avoid incoming mail while messing with INBOX
if [ -e "/var/mail/$USER" ]; then
	echo "Locking INBOX"
	mail-lock
	mail-touchlock &
	# Save the PID of the mail-touchlock process
	BADGER="$!"

	init_inbox

	# Convert INBOX if not empty
	if [ -s "/var/mail/$USER" ]; then
		mb2md -m
	fi

	promote_inbox

	# Purge old INBOX
	echo -n '' > "/var/mail/$USER"

	# Allow incoming mail again
	kill "${BADGER}"
	mail-unlock
	echo "INBOX unlocked again"
fi

# We want inbox initialized and promoted, even if no mailspool existed
init_inbox
promote_inbox

# Convert secondary mailboxes
if [ -d ~/mail ]; then
	mv ~/mail ~/mail.abandoned
	mb2md -R -s mail.abandoned
	# Grab dovecot subscriptions
	if [ -f ~/mail/.subscriptions ]; then
		mv ~/mail/.subscriptions ~/Maildir/"$subscriptions"
	# ...or UW-imap ones
	elif [ -f ~/.mailboxlist ]; then
		mv ~/.mailboxlist ~/Maildir/"$subscriptions"
	fi
fi