#!/bin/perl

die "usage: parse vote-directory" unless ($#ARGV == 0);
die "can't cd to $ARGV[0]" unless chdir($ARGV[0]);

#
# valid voting options
#

die "can't open options" unless open(OPT, "./options");

while (<OPT>) {
  chop;
  $opt{$_} = 1 unless ($_ eq "");
}
close(OPT);

die "can't open randlist" unless open(RNDLIST, "./randlist");

while (<RNDLIST>) {
  chop;
  ($addr, $numb) = split(/ /);
  $valid{"$numb"} = 1;
}
close(RNDLIST);

#
# parse header
#

while (<STDIN>) {
  chop;
  last if ($_ eq "");
  y/A-Z/a-z/;          # lower case
  if (/^from: /) {
    s/from: //;
    $from = $_;
    next;
  }
  if (/^reply-to: /) {
    s/reply-to://;
    $repl = $_;
    next;
  }
  if (/^date: /) {
    s/date://;
    $date = $_;
    next;
  }
  next unless /^subject: /;
  next unless (/#(\d+)/);
  $blt = $1;
}

$frm = $from;
$from = $repl if ($repl ne "");

if (!defined($blt) || $valid{"$blt"} == 0) {
  if ($from ne "") {
    system("/bin/echo \"$date error: no valid ballot # '" . 
			$from . "'\" >> ./errors");
    die unless open(MAIL, 
      "|v6mail -s 'Vote Error: no ballot number' '" . $from . "'");
    print MAIL "\nThe vote counter received your ballot but could not\n process it because the subject line did not contain a valid ballot\n number.  Please vote again.\n";
    close(MAIL);
  }
  exit(1);
}

#
# parse body
#

while (<STDIN>) {
  chop;
  s/ //g;
  s/\t//g;
  y/A-Z/a-z/;          # lower case
  $vote = $_;
  if ($opt{$vote}) {
    $voted = 1;
    while (<STDIN>) {
      chop;
    }
    last;
  }
}


if ($voted == 0) {
  if ($from ne "") {
    system("/bin/echo \"$date error: no vote '" . $from . "'\" >> ./errors");
    die unless open(MAIL, 
	"|v6mail -s 'Vote Error: no vote' '". $from . "'");
    print MAIL "\nThe vote counter received your ballot but could not\n process it because it did not contain a valid vote!\n Please vote again.\n";
    close(MAIL);
  }
  exit(1);
}

#
# at this point: $vote is vote, $from is from, $blt is ballot number
#

#
# check to see if user has already voted
#
# note: this isn't fool-proof, it is a quick check that handles most cases
# 	we will do a final check when we do the official tally
#

die "opening already" unless open(ALREADY,"./already");
while (<ALREADY>) {
  chop;
  if ($_ == $blt) {
    if ($from ne "") {
      system("/bin/echo \"$date error: dup vote '" . $from . "'\" >> ./errors");
      die "open mail" 
	unless open(MAIL, 
	  "|v6mail -s 'Vote Error: duplicate vote' '" . $from . "'");
      print MAIL 
          "\nThe vote counter received your ballot but did not process\n it because you have already voted.\n";
      close(MAIL);
    }
    exit(1);
  }
}
close(ALREADY);

system("/bin/echo $blt >> ./already");

system("/bin/echo $blt >> ./vote.$vote");


if ($from ne "") {
  die unless open(MAIL, "|v6mail -s 'Vote Received' '" . $from . "'");
  print MAIL 
      "\nThe vote counter received and recorded your ballot.  Thanks for voting!\n";
  close(MAIL);
}

exit 1;
