#!/usr/bin/perl

open(PINTAB, "< /usr/lib/pq/pqpin.tab") || die "I Can't open PIN table file: $!\n";

#load up the pin database into memory
while ($aline = <PINTAB>) {
	while ( ($aline =~ /^#/) && ($aline = <PINTAB>)) {
	#The the line is a comment, just eat it
	}
	($addressee[$pincount], $pin[$pincount], $modemnum[$pincount], $maxmesg[$pincount]) = split(' ', $aline);
	$pincount++;
}

while ($aline = <STDIN>) {
	
	@thefields = split(' ', $aline);

	if(@thefields[0] eq "From:") {
		chop($aline);
		$fromline = $aline;
	}

	if(@thefields[0] eq "To:") {
		chop($aline);
		@to = split(/\@/,$thefields[1]);
		$to = $to[0];

		$thispincount = 0;
		while(($thispincount < $pincount) && ($to ne $addressee[$thispincount])) {
			$thispincount++;
		}

		if($to ne $addressee[$thispincount]) {
			die "The addressee doesn't appear to be in the database!\n";
		}
	}

	if(@thefields[0] eq "Subject:") {
		chop($aline);
		$subjectline = $aline;
	}
}

	#the email will just be passed along
	$pageline = sprintf("%s, %s", $fromline, $subjectline);

	if(length $pageline > 191) {
		$mesg = sprintf("New Email: %s", $pageline);
		$mesg = substr($mesg,0,202);
		printf("Message too long, here is the message:%s\nHere is its len:%d", $mesg, length $mesg );
	}
	$mesg = sprintf("New Email: %s", $pageline);

	$sum = 31;	#to account for stx cr cr etx
	for ($i = 0; $i < length($pin[$thispincount]); $i++) {
		$sum +=  ord(substr($pin[$thispincount], $i,1));
	}


	if (length($mesg) > 231) { die "\7The message is greater than 230 characters!\n"}
	for ($i = 0; $i < length($mesg); $i++) {
		$sum +=  ord(substr($mesg, $i,1));
	}

	$sumstr = sprintf("%lx", $sum);
	$sumstr = substr($sumstr,length($sumstr)-3,3);

	$sumstr =~ s/a/:/g;
	$sumstr =~ s/b/;/g;
	$sumstr =~ s/c/</g;
	$sumstr =~ s/d/=/g;
	$sumstr =~ s/e/>/g;
	$sumstr =~ s/f/?/g;

	open(MESGOUT, ">> /var/spool/pq/$modemnum[$thispincount]") || die "I Can't open message output file: $!\n";
	chmod 666, MESGOUT;
	printf(MESGOUT "%s\n", $pin[$thispincount]);
	printf(MESGOUT "%s\n", $mesg);
	printf(MESGOUT "%s\n\n", $sumstr);
	close(MESGOUT);
