#!/usr/bin/perl

# This script is to unconvert from Maildir to mbox after running the 
# convert2maildir.pl script, but BEFORE ADDITIONAL MAIL DELIVERY. It expects
# the same userlist.txt file to be in the local directory, just like 
# convert2maildir.pl.

# Bugs, caveats, and licence are the same as convert2maildir.pl

use strict;

my $username;
my $homedir;
my $mblist;
my $hmdir;
my $qmail;
my $folder;
my $folderpath;
my $cmd;

open (USERS,"userlist.txt") ||die "Cannot open userlist.txt\n";

while (<USERS>)
{
	chop();
	next if /^#/;
	next if /^ /;

	$username = $_;
	$homedir = (getpwnam("$username"))[7];
        $mblist = $homedir . "/.mailboxlist";
        $hmdir = $homedir . "/Maildir/";
	$qmail = $homedir . "/.qmail";

	if (-e $mblist)
	{
		open (MBLIST,$mblist);
		while (<MBLIST>)
		{
			chop();
			$folder = $_;
			$folderpath = $homedir . "/" . $_ . ".gz";

			if (-e $folderpath)
			{
				print "Processing folder $folderpath\n";
				$cmd = "/bin/gunzip \"$folderpath\"";
				system($cmd);
			}
			else
			{
				print "Error processing $folderpath\n";
			}
		}

		if ((stat($qmail))[7] != 11) # .qmail is not ./Maildir/
		{
			print "\t Qmail file has changed:\n";
			open (QMAIL,"$qmail");
			while (<QMAIL>)
			{
				print "\t$_";
			}
			close (QMAIL);
		}
		else
		{
			print "\tUpdating qmail file\n";
			open (QMAIL,">$qmail");
			print QMAIL "./INBOX\n";
			close(QMAIL);
		}
		close(MBLIST);
	}
	else
	{
		print "ERROR OPENING MAILBOX LIST $mblist!!!\n";
	}

	if (-e $hmdir)
	{
		print "Removing Maildir\n";
		$cmd = "/bin/rm -rf $hmdir";
		system($cmd);
	}
}
close (USERS);

