#!/usr/bin/perl -w

my $mq = `sudo mailq`;

while ($mq =~ s/^\d\d[dm]  \d+(?:\.\d)?K ([0-9a-zA-Z]{6}-[0-9a-zA-Z]{6}-[0-9a-zA-Z]{2}) <(?:root\@tools\.wmflabs\.org)?>(?: \*\*\* frozen \*\*\*)?\n          (([-a-z0-9]+)\@tools-(?:dev|exec-02|login|master|webserver-01)\.pmtpa\.wmflabs)\n\n//) {
    my $mid = $1;
    my $oldmail = $2;
    my $localpart = $3;
    if (!system ('sudo', 'exim', '-Mf', $mid)) {
        if (!system ('sudo', 'exim', '-Mar', $mid, $localpart . '@tools.wmflabs.org')) {
            if (!system ('sudo', 'exim', '-Mmd', $mid, $oldmail)) {
                if (!system ('sudo', 'exim', '-Mt', $mid)) {
                    printf "Handled mid %s.\n", $mid;
                }
            }
        }
    }
    printf "MID = %s, OLDMAIL = %s, LOCALPART = %s\n", $1, $2, $3;
    # die ("Handle only one.");
}

die ($mq);
