#! /usr/bin/perl
# fixscript will replace this line with code to load INN::Config

# Author:       James Brister <brister@vix.com> -- berkeley-unix --
# Start Date:   Fri, 25 Apr 1997 14:11:23 +0200
# Project:      INN
# File:         innmail
# Description:  A simple replacement for UCB Mail to avoid nasty security
#               problems.
#
# Various bug fixes, code and documentation improvements since then
# in 1998, 1999, 2007, 2009, 2011, 2021-2024.

use strict;
use warnings;

use Getopt::Std;

# Define variables Getopt::Std uses for --help and --version.
$Getopt::Std::STANDARD_HELP_VERSION = 1;
our $VERSION = $INN::Config::version;
$VERSION =~ s/INN //;

$0 =~ s!.*/!!;

die "$0: No mta parameter defined in inn.conf.\n"
  if !defined($INN::Config::mta);

my $sm = $INN::Config::mta;

die "$0: MTA path is not absolute in inn.conf\n" unless ($sm =~ m!^/!);

my $usage = "Usage:
  $0 [-h] [-a header] [-s subject] addresses

Options:
  -a header    Adds the specified header field
               (for instance 'Auto-Submitted: auto-generated')
  -h           Prints this help message
  -s subject   Sets the Subject header field body of the mail

  addresses is a space-separated list of mail addresses.

  Reads stdin for message body.
  MTA used: $sm
";

sub HELP_MESSAGE {
    print $usage;
    exit(0);
}

my (%opt, @addrs);
getopts("a:hs:", \%opt) || die $usage;

HELP_MESSAGE() if defined($opt{'h'});

if (!defined($opt{'s'})) {
    warn "No subject given.  Hope that's OK.\n";
    $opt{'s'} = "NO SUBJECT";
} else {
    $opt{'s'} =~ s/\n+\Z//;
}

# Fix up any addresses.
foreach (@ARGV) {
    s![^-a-zA-Z0-9+_.@%]!!g;

    push(@addrs, $_) if ($_ ne "");
}

die "$0: No addresses specified\n\n$usage" unless @addrs;

if ($sm =~ m!%s!) {
    $sm = sprintf $sm, join(' ', @addrs);
} else {
    $sm .= " " . join(' ', @addrs);
}

my @smarr = split(/\s+/, $sm);

(my $t = $INN::Config::mta) =~ s!\s.*!!;
die "$0: MTA variable definition is changed after substitution\n"
  if ($t ne $smarr[0]);

die "$0: MTA executable doesn't appear to exist: $smarr[0]\n"
  if !-x $smarr[0];

# Startup MTA without using the shell.
my $pid = open my $MTA, '|-';
if ($pid == 0) {
    exec(@smarr) || die "$0: exec of $sm failed: $!\n";
} elsif ($pid < 0) {
    die "$0: Fork failed: $!\n";
}

print $MTA "To: ", join(",\n\t", @addrs), "\n";
print $MTA "Subject: $opt{'s'}\n";
print $MTA "$opt{'a'}\n" if defined($opt{'a'});
print $MTA "\n";
while (<STDIN>) {
    print $MTA $_;
}
close $MTA;
exit;
