#!/bin/sh

set -e

if [ ! -f /usr/bin/mb2md ]; then
	echo 'ERROR: mb2md not installed!'
	exit 1
fi

if [ -f ~/.procmailrc ]; then
	echo 'ERROR: ~/.procmailrc exists - must be handled manually...!'
	exit 1
fi

echo 'DEFAULT=$HOME/Maildir/' > ~/.procmailrc

# Convert secondary mailboxes first
# (reduces risk of clashing with new incoming mail)
mv ~/mail ~/mail.abandoned
mb2md -s mail.abandoned

#FIXME: check spool file lock before reading the spool file
if [ -f "/var/mail/$USER" ]; then
	mb2md -m
	echo -n '' > "/var/mail/$USER"
fi

# 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