#!/usr/local/bin/perl

# find forwards to a particular target
# qmail_find_forwards -d aol.com
# Copyright 2008 Jeremy Kister.  http://jeremy.kister.net./

use strict;
my %paths;

our($opt_v,$opt_f,$opt_p,$opt_d);
use Getopt::Std;
getopts('vf:d:p');

die "use -v or -f <filename>\n" unless($opt_v || $opt_f);
die "use -d <domain>\n" unless($opt_d);
# -p for pretty

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;
my %copy = %paths;

if($opt_f){
	$| = 1;
	open(LOG, ">$opt_f") || die "cannot write to $opt_f: $!\n";
}
while(my($domain,$dir) = each %paths){
	print "working on $domain\n" if($opt_v);
	if(opendir(D, $dir)){
		# open vpasswd, look for .qmail inside Maildirs
		if(open(V, "${dir}/vpasswd")){
			my $n=0;
			while(<V>){
				$n++;
			   if(/^([^:]+):[^:]+:\d+:\d+:[^:]*:([^:]+):/){
         		my $mailbox = $1;
         		my $maildir = $2;
					if(open(F, "$maildir/.qmail")){
						my $l=0;
						while(<F>){
							chop;
							$l++;
							if(/\@${opt_d}/){
								if($opt_p){
									s/^&//;
									warn "${mailbox}\@${domain}: $_\n" if($opt_v);
									print LOG "${mailbox}\@${domain}: $_\n" if($opt_f);
								}else{
									warn "$maildir/.qmail (line $l): $_\n" if($opt_v);
									print LOG "$maildir/.qmail (line $l): $_\n" if($opt_f);
								}
							}
						}
						close F;
					}else{
						unless(-d $maildir){
							warn "No maildir for $mailbox\@$domain ($dir)\n" if($opt_v);
							print LOG "No maildir for $mailbox\@$domain ($dir)\n" if($opt_f);
						}
					}
				}else{
					warn "Invalid syntax at ${dir}/vpasswd:$n\n" if($opt_v);
					print LOG "Invalid syntax at ${dir}/vpasswd:$n\n" if($opt_f);
				}
			}
			close V;
		}else{
			warn "cannot open ${dir}/vpasswd: $!\n"  if($opt_v);
			print LOG "cannot open ${dir}/vpasswd: $!\n"  if($opt_f);
		}
		foreach my $file (grep {/^\.qmail-/} readdir D){
			if(open(F, "${dir}/${file}")){
				my $n=0;
				while(<F>){
					chop;
					$n++;
					next if(/^#/);
					if(/\@${opt_d}/){
						if($opt_p){
							s/^&//;
							my ($user) = $file =~ /.qmail-(.+)/;
							warn "${user}\@${domain}: $_\n" if($opt_v);
							print LOG "${user}\@${domain}: $_\n" if($opt_f);
						}else{
							warn "${dir}/${file} (line $n): $_\n" if($opt_v);
							print LOG "${dir}/${file} (line $n): $_\n" if($opt_f);
						}
					}
				}
				close F;
			}else{
				warn "could not open ${dir}/${file}: $!\n" if($opt_v);
				print LOG "could not open ${dir}/${file}: $!\n" if($opt_f);
			}
		}
		closedir D;
	}else{
		warn "error with $domain: $dir does not exist\n"  if($opt_v);
		print LOG "error with $domain: $dir does not exist\n"  if($opt_f);
	}
}
