#!/usr/athena/bin/perl
@ACRON = $ENV{ACRON} || </mit/sipb/share/acron/acron*>;
$DEST = "sipb-whats\@mit.edu";

@entries = ();
if (@ARGV == 0) {
    print "What is what? ";
    $a = <STDIN>;
    $a =~ s/\s*$//;
} else {
    $a = $ARGV[0];
}

$a = "\U$a";

die "\nNo acron to look up\n" unless $a;

foreach (@ACRON) {
    if (open(IN, $_)) {
	push(@entries, grep(/^$a\t/i,<IN>));
	close(IN);
    }
}

if (@entries) {
#    if (@ARGV > 1) { # expansion supplied
#	print scalar(@entries), " occurrences found.\n";
#    }
    $lastbase = $notes = '';
    $first = 1;
    foreach (sort @entries) {
	s/\s*$//;
	if (/^(.*\S)(\s*\(.*\)|\s*\[.*\])$/) {
	    if ("\L$1" eq "\L$lastbase") {
		$notes .= $2;
	    } else {
		print "$lastbase$notes\n" unless $first;
		$lastbase = $1;
		$notes = $2;
	    }
	} else {
	    if (!$first && "\L$_" ne "\L$lastbase") {
		print "$lastbase$notes\n";
	    }
	    $lastbase = $_;
	    $notes = '';
	}
	$first = 0;
    }
    print "$lastbase$notes\n";
    if (@ARGV < 2) { # User didn't supply expansion, and we had a match.
	exit;
    } else {
	print "Still want to add $a? ";
	$yn = <STDIN>;
	if ($yn !~ /^[Yy]/) {
	    exit;
	}
    }
} elsif (@ARGV < 2) {
    # no matches, and no expansion supplied; ask for expansion
    print "What does $a stand for? ";
    $def = <STDIN>;
    $def =~ s/\s*$//;
}

if (@ARGV > 1) {
    $def = join(' ', @ARGV[1..$#ARGV]);
}

die "\nNo definition given\n" unless $def;

print "Would you like this entry to appear in the database?\n";
print "Answering 'yes' will send electronic mail on your behalf\n";
print "requesting that this acronym be added to our database. (y/n) ";
$yn = <STDIN>;
if ($yn =~ /^[Yy]/) {
    print STDERR $yn;
    if (-x '/usr/sbin/sendmail') {
	$sendmail = '/usr/sbin/sendmail';
    } elsif (-x '/usr/lib/sendmail') {
	$sendmail = '/usr/lib/sendmail';
    } else {
	$sendmail = 'sendmail';
    }
    open (SENDMAIL, "|$sendmail -t") || die "Unable to run sendmail";
    print SENDMAIL <<EOF;
To: $DEST
Subject: New acron entry: $a

$a\t- $def
EOF
    close(SENDMAIL);
    print "Entry sent for database addition:\n";
    print "$a\t- $def\n";
}
