#!/usr/bin/env perl
use strict;

my $from="";
my $ctype = "";
my $hdrname = "";

while (<>) {
  my $value;
  
  chomp $_;
  last if (/^$/);
  if (/^([^ \t][^:]*): (.*)$/) {
    $hdrname = $1;
    $value = $2;
  } else {
    s/^[ \t]*//;
    $value = $_;
  }
  if ($hdrname =~ /^From$/i) {
    $from .= $value;
  } elsif ($hdrname =~ /^Content-Type$/) {
    $ctype .= $value;
  } 
}

$from =~ s/\([^\)]*\)//g; # remove comments
$from =~ s/[ \t\r\n]+/ /g; # pack whitespace
$from =~ s/ *@ */@/g; # remove lwsp around @
$from =~ s/ *\. */./g; # remove lwsp around .

exit 0 if !($from =~ /Timo Sirainen/ || $from =~ /\btss\@iki.fi\b/);

exit 100 if !($ctype =~ /multipart\/signed.*boundary="([^"]+)"/);
my $boundary = $1;

# find beginning
while (<>) {
  chomp $_;
  last if ($_ eq "--$boundary");
}

# get the data to be verified
my $gpgstring = "";
while (<>) {
  chomp $_;
  last if ($_ eq "--$boundary");
  $gpgstring .= "$_\r\n";
}
$gpgstring =~ s/\r\n$//; # last crlf belongs to boundary

# get the signature
my $sig = "";
my $found = 0;
while (<>) {
  $sig .= $_;
  last if ($_ eq "--$boundary--");
  $found = 1 if (/^-----BEGIN PGP SIGNATURE-----/);
}

exit 101 if !$found;

# write signature to temp file
my $sigfname = "tmpsig.$$";
my $outfname = "tmpout.$$";
my $f;
open $f, ">$sigfname";
print $f $sig;
close $f;

# execute gpg
my $gpg;
open $gpg, "|HOME=/home/mailfilter /usr/bin/gpg --verify $sigfname - 2>$outfname" or die $!;
print $gpg $gpgstring;
close $gpg;
my $ret = $?;

unlink $sigfname;

if ($ret ne "0") {
  unlink $outfname;
  exit $ret;
}

my $sigfrom = "";
open $f, $outfname;
while (<$f>) {
  $sigfrom = $1 if (/^gpg: Good signature from "([^"]*)"/);
}
close $f;
unlink $outfname;

exit 103 if ($sigfrom ne 'Timo Sirainen <tss@iki.fi>' &&
	     $sigfrom ne 'Timo Sirainen <timo.sirainen@movial.fi>');

exit 0
