#!/usr/bin/perl -w
use strict;

my $splitsize   = exists $ENV{'SPLITSIZE'} ? int($ENV{'SPLITSIZE'}) : 250000;
my $sendmail = exists $ENV{'SENDMAIL'} ? $ENV{'SENDMAIL'}
                        : '/usr/sbin/sendmail';
my $mail_cmd = "$sendmail -oi -t";
my $part_overhead = 50;
my ($hdr, $newhdr, @body, $bodypart);
my ($subj, $msglen, $lastpart, $msgnum);
my ($msgid, $msgdomain);

##
## Output $bodypart, changing the subject and message id as needed.
##
sub sendmsg() {
      ++$msgnum;
      $newhdr = $hdr;
      $newhdr =~
          s/Subject:[^\n]*\n/Subject: $subj (part $msgnum or $lastpart)\n/mi;
      $newhdr =~ s[Message-Id:[ ]*<[^@]*@[^>]*>\n]
                  [Message-Id: <${msgid}.${msgnum}\@${msgdomain}>\n]mi;
      open(MSGOUT, "| $mail_cmd");
      print MSGOUT $newhdr;
      print MSGOUT $bodypart;
      close(MSGOUT);
}

##
## Collect the original message header,
## and extract the original subject and message id.
##
while (<>) {
    last if (/^\n$/);
    $hdr .= $_;
    $subj = $1 if (m/^Subject:[ ]*([^\n]*)\n$/i);
    if (m/^Message-Id:[ ]*<([^@]*)@([^>]*)>\n$/i) {
       $msgid = $1;
       $msgdomain = $2;
    }
}
$hdr .= "\n";
if (! $subj ) { $subj = '<none>'; }
if (! $msgid ) { $msgid = 'foo'; }
if (! $msgdomain ) { $msgdomain = 'bar'; }

##
## save each line in the body, and count the total number of
## message parts that will be produced.
##
$msglen = length($hdr) + $part_overhead;
while (<>) {
  if (($msglen + length()) > $splitsize) {
      ++$lastpart;
      $msglen = length($hdr) + $part_overhead + length();
  }
  $msglen += length();
  push @body, $_;
}
++$lastpart;

##
## output each message part
##
$msglen = length($hdr) + $part_overhead;
$bodypart = '';
foreach (@body) {
  if (($msglen + length()) > $splitsize) {
      sendmsg();
      $msglen = length($hdr) + $part_overhead + length();
      $bodypart = '';
  }
  $msglen += length();
  $bodypart .= $_;
}
sendmsg();
