#!/usr/bin/perl -w

&main();

sub main {
  my $groupby= 1000;
  my $outdir;
  if ($#ARGV != 1) {
    print STDERR "usage: $0 inputfile outdirectory\n";
    exit(1);
  } else {
    my $file= $ARGV[0];
    open(INF, "<$file") || die "could not open $file for reading\n";
    $outdir= $ARGV[1];
    (-d $outdir) || die "$outdir is not a directory\n";
  }
  my $filecounter=1000000;
  my $indircounter= $groupby + 1; # start with new directory
  my $groupnr= 10000;
  my $actdir;
  while (!eof(INF)) {
    my ($useit, $mail, $subject, $from, $to)= readOneMail(INF);
    if ($useit) {
      $filecounter++;
      $indircounter++;
      if ($indircounter >= $groupby) {
	print STDERR "$filecounter\r";
	$groupnr++;
	$indircounter= 0;
	$actdir= $outdir . "/" . $groupnr;
	mkdir ($actdir, 0775) || die "could not create directory $actdir\n";
      }
      # if ($subject =~ /incremental|add/i) {
      if (1==1) { 
	my $file= $actdir . "/pksi" . $filecounter;
	open(OUT, ">$file") || die "could not create $file\n";
	print OUT $mail;
	close(OUT);
      } else {
	print STDERR "\n ignoring mail with subject: $subject\n";
      }
    }
  }
  print "\nCreated $filecounter files\n";
}

sub readOneMail {
  my ($fh)= @_;
  my ($to, $from, $mail, $subject, $line, $startPGP, $endPGP);
  my $end= eof($fh);
  $mail= "";
  $startPGP= (0==1);
  $endPGP= (0==1);
  while (! $end) {
    $line= <$fh>;
    if ($line =~ /^Subject:/) { $subject= $line; }
    if ($line =~ /^From:/)    { $from= $line; }
    if ($line =~ /^To:/)      { $to= $line; }
    if ($line =~ /^-----BEGIN PGP PUBLIC KEY BLOCK-----/)  { $startPGP= (1==1); }
    if ($startPGP && (! $endPGP)) {
      # add only PGP keymaterial
      $mail.= $line;
    }
    if ($line =~ /^-----END PGP PUBLIC KEY BLOCK-----/)    { $endPGP= (1==1); }
    $end= $endPGP || eof($fh);
  }
  return ($endPGP, $mail, $subject, $from, $to);
}

0;
