#!/usr/local/bin/perl

# chkusr concept code for serialmail
# if I output 1, accept mail.  

my $SERIALMAIL_SUPPORT = 1;

if(defined($SERIALMAIL_SUPPORT)){

	### just for this concept code
	my $email = shift;
	my ($user,$domain) = split /\@/, $email;
	die "bad syntax\n" unless(defined($user) && defined($domain));
	###

	my $homedir = '/var/qmail/autoturn';
	unless(-d $homedir){
		print "1"; # cant find homedir for queue;  queue locally
		exit;
	}
	
	open(V, '/var/qmail/control/virtualdomains') || die "cannot open virtualdomains: $!\n";
	while(<V>){
		chop;
		if(/^${domain}:autoturn-(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/){
			my $ip = $1;
			$ip =~ s/\./:/g; # use colon's in the ip address instead of dots
			if(open(Q, "$homedir/.qmail-${ip}-default")){
				my $firstline = <Q>;
				if($firstline =~ /bounce-no-mailbox/){ # no ^ or $
					# bouncing enabled
					if($user eq 'default'){
						print "0"; # administrative address
					}else{
						my ($first,$rest) = split /-/, $user; # we allow extension addresses
						if(-f "$homedir/.qmail-${ip}-${first}"){
							print "1"; # username exists
						}else{
							print "0"; # username doesnt exist
						}
					}
				}else{
					print "1"; # bouncing not enabled
				}
				close Q;
			}else{
				print "1"; # cant open .qmail-$ip-default, queue locally
			}
			last;
		}
	}
	close V;
}
