#!/usr/local/bin/perl
#
# This program takes a list of email addresses and expands them by connecting
# to the appropriate machines and asking the sendmail daemon on each machine
# how the address will be interpreted.
#
# Stig@netcom.com	Sept 1994

($ARGV[0] eq '-d') && ($debug=1,shift);

foreach $addr (@ARGV) {
    @exn= &expn($addr);
    print $addr,":\n  ", join("\n  ", @exn), "\n";
}


sub expn {
    local ($addr) = @_;
    local ($user, $host, $expansion, $tn_pid);

    $addr =~ m/(\w+)(@([\w.-]+))?/ || return "bad address";
    $user = $1;
    $host = ($3 || "localhost");
    print "expanding $user at $host\n" if $debug;

    pipe(TTI,TI);
    pipe(TO,TTO);
    
    select TI; $|=1;
    select TTO; $|=1;
    select STDERR; $|=1;

    if (!($tn_pid= fork())) {
	close (TI); close (TO);

	if ($debug) {

	    pipe(DI,DDI);
	    pipe(DDO,DO);
	
	    select DDI; $|=1;
	    select DO; $|=1;

	    if (!fork()) {
		foreach (DI, DO, TTO, DDO) { close $_; }
		while (<TTI>) { print STDERR "in:  $_"; print DDI; }
		exit 0;
	    }
	    if (!fork()) {
		foreach (DI, DO, TTI, DDI) { close $_; }
		while (<DDO>) { print STDERR "out: $_"; print TTO; }
		exit 0;
	    }
	    close(TTO),close(TTI);
	    open(TTI,"<&DI") || die "debugging whacked: $!";
	    open(TTO,">&DO") || die "debugging whacked: $!";
	}

	open (STDIN, "<&TTI") || die "reopen stdin";
	open (STDOUT,">&TTO") || die "reopen stdout";
	open (STDERR,">/dev/null") || die "reopen stderr";
	exec ("telnet", $host, "25");
	die "how did I get here?";
    }
    close(TTI), close(TTO);

    ($_=<TO>) until m/^220 /;
    print TI "expn $user \n";

    do {
	$_=<TO>;
	$expansion .= $_;
    } until m/^\d\d\d /;

    print TI "quit\n";

    scalar(<TO>);		# wait for the goodbye message
    close(TI), close(TO);

    chop $expansion;
    @exp = split(m/\n/,$expansion);
    grep(s/^\d\d\d[- ]//, @exp);
    print "$user\@$host : ", join(", ",@exp), "\n" if $debug;
    return @exp
}
