#!/usr/local/bin/perl

# make sure all .qmail-defaults contain something smelling valid
# Copyright 2008 Jeremy Kister.  http://jeremy.kister.net./

use strict;
my ($y,$m,$d) = (localtime())[5,4,3];
$y += 1900;
$m++;
my $mon = sprintf('%.2d', $m);
my $day = sprintf('%.2d', $d);

my $date = $y . $mon . $day;

my(%dir,%nuked);
my $DEBUG;

opendir(D, '/var/qmail/queue/mess/') || die "cannot opendir queue/mess: $!\n";
my @subdirs = (grep {!/^\./} readdir D); # conf-split
closedir D;

# trim log,
my @log;
if(open(LOG, "/export/home/misc_logs/defaultbounce")){
   while(<LOG>){
      push @log, $_;
   }
   close LOG;
   my $i=1;
   open(LOG, ">/export/home/misc_logs/defaultbounce.tmp") || die "cannot write to defaultbounce.tmp: $!\n";
   foreach my $line (reverse @log){
      print LOG $line;
      last if($i == 10000);
      $i++;
   }
   close LOG;

   rename("/export/home/misc_logs/defaultbounce.tmp","/export/home/misc_logs/defaultbounce")
     || die "cannot rename tmp: $!\n";
}
## end trim log


open(LOG, ">>/export/home/misc_logs/defaultbounce") || die "cannot open defaultbounce for append: $!\n";


my $V = (shift) ? 1 : undef;

my %paths;
print "gathering mx authoritative data..\n";
open(A, '/var/qmail/users/assign') || die "cannot open assign: $!\n";
while(<A>){
   if(/^\+.+-:([^:]+):\d+:\d+:([^:]+):-::$/){
      if((-f "$2/vpasswd") && (! -l "$2")){
         $paths{$1} = $2;
      }
   }
}
close A;

while(my($domain,$dir) = each %paths){
	print "working on $domain...\n" if($V);
	my $rename = 0;
	if(open(V, "$dir/.qmail-default")){
		open(N, ">$dir/.qmail-default.new") || die "cannot write to $dir/.qmail-default.new: $!\n";
		my $line=0;
		while(<V>){
			$line++;
			if(/bounce-no-mailbox/){
				print N;
				next;
			}elsif(/delete/){
				# change these to bounce-no-mailbox
				print LOG "[${date}]: $dir/.qmail-default:$line (changed to bounce-no-mailbox)\n";
				print N "|/home/vpopmail/bin/vdelivermail '' bounce-no-mailbox\n";
				$rename = 1;
			}elsif(/\'\'\s(\S+)/){
					my $maildir = $1;
					if($maildir =~ /\S+\@\S+\.\S+/){
						print N;
						next;
					}
					if(-d $maildir){
						# find out if this mailbox is being used
						my $ago = ($^T - 5184000);  # 60 days ago
						if((stat("$maildir/lastauth"))[9] < $ago){
							print LOG "[${date}]: $dir/.qmail-default:$line (unchecked default box)\n";
							print N "|/home/vpopmail/bin/vdelivermail '' bounce-no-mailbox\n";
							$rename = 1;
							# now delete mailbox, or nuke the maildir if postmaster
							#my ($user) = $maildir =~ s#.*/##g; ## WTF??
							my $user = $maildir;
							$user =~ s#.*/##g;
							if($user eq 'postmaster'){
								print LOG "[${date}]: nuking mail for postmaster\@$domain\n";
								foreach my $place ('new','cur'){
									opendir(D, "$maildir/Maildir/$place") || die "cant opendir $place: $!\n";
									foreach my $file (grep {!/^\./} readdir D){
										unlink("$maildir/Maildir/$place/$file") || die "cant unlink $file: $!\n";
									}
									closedir D;
								}
							}else{
								print LOG "[${date}]: deleting ${user}\@${domain}\n";
								my ($error) = `/home/vpopmail/bin/vdeluser $user\@$domain 2>&1`;
								warn "$error\n" if($error);
							}
						}else{
							print N;
						}
					}else{
						print LOG "[${date}]: $dir/.qmail-default:$line (maildir doesnt exist)\n";
						print N "|/home/vpopmail/bin/vdelivermail '' bounce-no-mailbox\n";
						$rename = 1;
					}
			}
		}
		close V;
		close N;
		if($line > 1){
			print LOG "[${date}]: $dir/.qmail-default contains $line commands\n";
		}
		if($rename == 1){
			print LOG "[${date}]: renaming $dir/.qmail-default.new\n";
			rename("$dir/.qmail-default.new","$dir/.qmail-default") || die "cant rename $dir/.qm: $!\n";
			chown(32008,30011,"$dir/.qmail-default") || die "cant chown $dir/.qmail-default: $!\n";
		}else{
			unlink("$dir/.qmail-default.new") || die "cannot unlink $dir/.qmail-default.new";
		}
	}else{
		print LOG "[${date}]: no .qmail-default for $domain ($dir)\n";
	}
}

close L;
