#!/bin/sh
# -*- perl -*-
# This code allows us to start perl from our path or an environment variable
# rather than hardcoding a path into the #! line.  It works from sh or csh.
(exit $?0) && eval 'exec ${QPERLQ-perl} -x $0 ${1+"$@"}'
if (! $?QPERLQ) setenv QPERLQ perl
exec $QPERLQ -x $0 $argv:q

#!/usr/local/bin/perl -w
#
# $Id: resend_mail,v 1.8 1999/03/19 20:42:57 ejb Exp $
# $Source: /home/ejb/scripts/RCS/resend_mail,v $
# $Author: ejb $
#

require 5.002;
use strict;

my $whoami = ($0 =~ m,([^/\\]*)$,) ? $1 : $0;
#my $dirname = ($0 =~ m,(.*)[/\\][^/\\]+$,) ? $1 : ".";

my $count = 0;
while (@ARGV)
{
    my $arg = shift(@ARGV);
    if ($arg eq "-count")
    {
	$count = 1;
    }
    elsif ($arg =~ m/^-/)
    {
	&usage();
    }
    else
    {
	unshift(@ARGV, $arg);
	last;
    }
}

&usage() if (@ARGV < 1);
my $file = shift(@ARGV);
my $to = shift(@ARGV) || ($file =~ m,/([^/]+)$, ? $1 : $file);

my $t = $/;
$/ = "\n\nFrom ";
open(F, "<$file") || die "$whoami: failed to open $file: $!\n";
my @messages = (<F>);
close(F);
$/ = $t;
my $i;
for ($i = 0; $i < scalar(@messages) - 1; $i++)
{
    if ($messages[$i] =~ s/\nFrom $//s)
    {
	$messages[$i+1] =~ s/^/From /;
    }
}
$messages[-1] =~ s/\n\n$/\n/s;

# Hack: The POP/IMAP server RedHat uses puts this bogus message at the
# beginning of everyone's mail file.
if ($messages[0] =~
    m/Subject: DON\'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA/)
{
    shift(@messages);
}

if ($count)
{
    print scalar(@messages), "\n";
    exit 0;
}

if (@messages == 0)
{
    print "No mail in $file to resend.\n";
    exit 0;
}

print "Resending mail from file $file to address $to\n";

my @failures = ();
for ($i = 0; $i < scalar(@messages); $i++)
{
    $messages[$i] =~ m/^From ([^\s]+) /;
    printf("\n*** Sending message %d from %s\n", $i+1, $1);
    eval
    {
	&deliver($messages[$i], $1);
    };
    if ($@)
    {
	warn "*** ERROR: Failed to resend message: $@";
	push(@failures, $i+1);
    }
    else
    {
	print "*** Message succesfully delivered.\n";
    }
    # Pause to keep from hosing the mail server
    sleep 2;
}

print "\n";
if (@failures)
{
    print "The following messages were NOT delivered succesfully " .
	"(counting from 1):\n";
    for (@failures)
    {
	print "  $_\n";
    }
    exit 2;
}
else
{
    print "All messages were delivered succesfully.\n";
}

sub deliver
{
    my $msg = shift;
    open(SENDMAIL, "|/usr/sbin/sendmail $to") or
	die "$whoami: can't run sendmail: $!\n";
    print SENDMAIL $msg or die "$whoami: can't write to sendmail: $!\n";
    close(SENDMAIL) or die "$whoami: closing sendmail pipe failed: $!\n";
    my $r = $?;
    if ($r != 0)
    {
	die "$whoami: sendmail exited abnormally\n";
    }
}

sub usage
{
    print STDERR "Usage: $whoami mail_file [to_addr]\n";
    print STDERR "  To address defaults to last component of mail filename\n";
    exit 2;
}
