#!/usr/bin/perl --
# Semiautomatic configuration script for Debian's Smail package.
# Used after installation to configure a mail system, and can be run
# at any later time (though --force may be needed).
# Copyright 1994 Ian Jackson.  There is NO WARRANTY.
# See /usr/doc/smail/copyright or type smail -bC for more information.

$|=1;

$etc='/etc';
$testmsg='smailtest';
if ($ARGV[0] eq '--force') { $force=1; shift; }

if (-f "$etc/smail/config") {
    if ($force) {
        print "Ignoring existing Smail configuration.\n";
    } else {
        print
'Your mail system (Smail) is already configured; I\'ll leave the
existing configuration untouched.  Use --force to ignore it.
';
        exit(0);
    }
}

$rfc1035_label_re= '[A-Za-z]([-0-9A-Za-z]*[0-9A-Za-z])?';
$rfc1035_domain_re= "$rfc1035_label_re(\\.$rfc1035_label_re)*";
$rfc1035_domain_explain=
    " Each component must start with a letter, end with an alphanum and contain\n".
    " only alphanums and hyphens.  Components must be separated by full stops.";

chop($syshostname=`hostname --fqdn`);
$? && die "hostname --fqdn gave non-zero exit code $?   $syshostname\n";

if ($syshostname !~ m/^$rfc1035_domain_re$/) {
    print STDERR "Error: system's FQDN hostname ($syshostname) doesn't match\n".
                 "RFC1035 syntax; cannot configure the mail system.\n";
    exit(1);
}

open(P,"</etc/passwd") || die "cannot read /etc/passwd: $!\n";
@passwd1=@passwd2=<P>;
close(P);
@redirusers= grep(s/^(\w+):([^:]+):(\d+):\d+:.*\n/$1/ &&
                  length($2) < 13 && $3 < 100, @passwd1);
$defaultpostmaster= (grep(s/^(\w+):([^:]+):(\d+):\d+:.*\n/$1/ &&
                          length($2) >= 13 && $3 >= 100, @passwd2))[0];
$redirinmessage= join(' ',@redirusers);
push(@redirusers,'');
$redirinalias= join(": root\n",@redirusers);

if (open(OI,"$etc/inetd.conf")) {
    @inetd=<OI>;
    close(OI);
    $newentry="smtp\tstream\ttcp\tnowait\troot\t/usr/sbin/tcpd\t/usr/sbin/in.smtpd\n";

    if (grep(m/^smtp\s+/,@inetd)) {
        if (grep(m/^smtp\s+/,@inetd) > 1) {
            &inetde("There are several entries for SMTP in /etc/inetd.conf\n");
        } elsif (!grep(m:^smtp\s+stream\s+tcp\s+nowait\s+root\s+\S+\s+\S*in\.smtpd\s+$:,
                       @inetd)) {
            &inetde(
"There is already an entry for SMTP in /etc/inetd.conf,
but I don't recognise it.  Here is what it looks like:
 ".join(' ',grep(m/^smtp\s+/,@inetd))
                    );
        }
    } elsif (grep(m/^\# *smtp\s+/ && m/\(will be restored by smail postinst\)$/,
                 @inetd)==1) {
        grep(m/^\# *smtp\s+/ && m/\(will be restored by smail postinst\)$/
             && s/^\# *// && s/\(will be restored by smail postinst\)$//, @inetd);
    } elsif (grep(m/^\# *smtp\s+/, @inetd)==1) {
        grep(m/^\# *smtp\s+/ && s/^\# *//, @inetd);
    } else {
        push(@inetd,$newentry);
    }
    $inetdconf=1;
}

sub inetde {
    do {
        print @_,
"Do you want to ignore this potential problem and configure your mail system
anyway, or would you rather not do so now ?   Configure now ?  (n/y) ";
	$!=0; defined($response=<STDIN>) || die "smailconfig: EOF/error on stdin: $!\n";
    } while ($response !~ m/^\s*[yn]?\s*$/i);
    $response =~ m/y/i || exit 1;
}


for (;;) {

    undef @files;


# Which major configuration ?
    next unless &query(
"I can do certain kinds of automatic configuration of your mail system, by
asking you a number of questions.  Later you may to confirm and/or correct
your answers.  In any case, comprehensive information on configuring Smail is
in smail(5) and in /usr/doc/smail/examples and /usr/doc/smail/guide.

You must choose one of the options below:
 (1) Internet site: you send and receive Internet mail on this
    machine, using SMTP over TCP/IP.
 (2) UUCP to smarthost (upstream site):
    You send and receive mail via UUCP; outbound mail is sent to your
    smarthost (probably your service provider) for routing and delivery.
 (3) Satellite system:
    No mail is to be delivered or routed here.  Any mail generated
    on this system is sent to a central mail switch using SMTP.
 (4) Local delivery only:
    You are not on a network.  Mail for local users is delivered.
 (5) No configuration:
    No configuration will be done now; your mail system will be broken and
    should not be used.  You must then do the configuration yourself later or
    run this script, /usr/sbin/smailconfig, as root.
Select a number from 1 to 5, from the list above.",
           'configtype',
           -f '/usr/sbin/inetd' ? '1' :
           -f '/usr/bin/uucp' ? '2' : '4',
           'm/^[12345]$/');

    if ($configtype == 5) {
        print "\nMail configuration skipped.\n";
        exit 0;
    }

    if ($configtype == 1 && !($inetdconf && -x '/usr/sbin/inetd')) {
        print "
Warning!  You don't appear to have the TCP/IP system installed.
Your mailer will not be able to send and receive SMTP without it.\n\n";
    } elsif ($configtype == 2 && !-x '/usr/bin/uux') {
        print "
Warning!  You don't appear to have UUCP installed.  In this configuration
your mailer will be unable to handle offsite mail without it.\n\n";
    }



# What are the hostnames for this system ?
    &query(
"What is the `visible' mail name of your system ?
This will appear on From: lines of outgoing messages.",
           'visiblename',
           $syshostname,
           'm/^$rfc1035_domain_re$/ ||
            &reswarn("This must conform to RFC1035\'s requirements.\n".
                     "$rfc1035_domain_explain")') || next if $configtype < 4;
    $visiblename= $syshostname if $configtype == 4;
    &setfileshort("mailname","$visiblename\n");
    
    &query(
"Does this system have any other names which may appear on incoming
mail messages, apart from the visible name above ($visiblename)
and the system's hostname ($syshostname) ?
If so enter them here, separated with spaces or commas.  If there are
none, say \`none'.",
           'hostnames',
           'none',
           '1', 'e') || next if $configtype < 3;
    @names= $configtype < 3 ? split(/[ \t,]+/,$hostnames) : ();
    $warnexh= 0;
    grep(((m/^$rfc1035_domain_re$/ ||
           ($warnexh= 1,
            (print STDERR "\n Warning - name \`$_' doesn't conform to RFC1035's".
                          " requirements.")))),
         @names);
    if ($warnexh) { print STDERR "\n$rfc1035_domain_explain\n"; }
    unshift(@names, $visiblename);
    unshift(@names, $syshostname) unless $syshostname eq $visiblename;
    $colonhostnames= 'hostnames='.join(':',@names);


# Is there a smarthost and what is it called ?
    &query(
"Do you have a smarthost available (and accessible via SMTP) ?

A smarthost is a system to which you forward mail you don\'t want to
deliver yourself; it presumably has better connectivity or routing
information than you do.  Commercial providers usually provide a
smarthost for their customers, and large organisations will often have
a site mail switch which can be used.  Use of a smarthost is strongly
recommended (you\'ll be able to specify exactly when to use it soon).

If a smarthost is available please enter its name (otherwise, \`none').",
           'smarthost',
           '',
           '$_ eq "" || m/^$rfc1035_domain_re$/ ||
            &reswarn("This must conform to RFC1035\'s requirements.\n".
                     "$rfc1035_domain_explain")',
           'e') || next if $configtype == 1;



# When should we use the smarthost ?
    &query(
"Do you wish to use the smarthost for:
 (1) All outbound mail.  This is good if your system is poorly
    connected, eg via dialup SLIP, as you don't have to talk
    to distant machines yourself, and it allows you to send out
    just one copy of a message for all its the remote recipients.
 (2) Mail that you have failed to find a way to route.  This
    means that mail for any unknown hosts or domains will be
    sent to the smarthost in the hope that it will know better;
    if it doesn\'t the smarthost should bounce it back to you.
    This is recommended for most situations, and usually results
    in faster end-to-end delivery than always using the smarthost.
 (3) Only mail to the \`awkward' UUCP and BITNET domains.
    These domains don't appear in the Internet routing tables,
    and how to reach them varies depending on your location.
    Use this if your smarthost\'s admin has asked you to avoid using
    the smarthost unnecessarily, or if it is unreliable or very slow.
Select a number from 1 to 3, from the list above.",
           'smartwhen',
           '2',
           'm/^[123]$/') || next if $configtype == 1 && length($smarthost);

    $usesmarthost = $configtype == 3 ? 4 :
                    length($smarthost) ? 4-$smartwhen : 0;



# What is smarthost/smartuser for satellite systems ?
    &query(
"You have to tell me where to send all locally-generated mail.
Using $visiblename will result in mail for local users being sent
to whatever system the rest of the world thinks deals with mail for
that address - that had better not be this machine, in that case.",
           'smarthost',
           $visiblename,
           'm/^$rfc1035_domain_re$/ ||
            &reswarn("This must conform to RFC1035\'s requirements.\n".
                     "$rfc1035_domain_explain")') || next if $configtype == 3;



# What is smarthost/smartuser for UUCP leaf nodes ?
    &query(
"You have to tell me where to send email bound for remote systems, by telling
me the UUCP name of your smarthost (probably your service provider).",
           'smarthost',
           '',
           '1') || next if $configtype == 2;



# Who is to receive postmaster mail ?
    &query(
"Mail for the \`postmaster' and \`root' accounts is usually redirected
to one or more user accounts, of the actual system administrators.
By default, I'll set things up so that mail for \`postmaster' and for
various system accounts is redirected to \`root', and mail for \`root'
is redirected to a real user.  This can be changed by editing /etc/aliases.

Note that postmaster-mail should usually be read on the system it is
directed to, rather than being forwarded elsewhere, so (at least one of)
the users you choose should not redirect their mail off this machine.

Which user account(s) should system administrator mail go to ?
Enter one or more usernames separated by spaces or commas .  Enter
\`none' if you want to leave this mail in \`root's mailbox - NB this
is strongly discouraged.  Also, note that usernames should be lowercase !",
           'postmasters',
           $defaultpostmaster,
           'm/^([-_a-z0-9]+[ \t,]*)*$/ ||
            &reswarn("\nUsernames must consist of lowercase alphanums, or - and _.\n")',
           'e') || next unless $configtype == 3;
    @postmasters= split(/[ \t,]+/,$postmasters);
    $rootalias= @postmasters ? "root: ".join(',',@postmasters)."\n" : '';



    &setfile('smail/config',
'# This is the main Smail configuration file.',
"

visible_name=$visiblename
-domains
$colonhostnames

". ($configtype =~ m/[13]/ ? 
'max_load_ave=5
smtp_accept_max=20
smtp_accept_queue=10
rfc1413_query_timeout=15

':''). ($configtype == 2 ? 
'spool_grade=C

':''). 
'require_configs
-second_config_file
-qualify_file
-retry_file
copying_file=/usr/doc/smail/copyright
max_message_size=10M

received_field="Received: \
    ${if def:sender_host\
       {from $sender_host ${if def:sender_host_addr ([$sender_host_addr]) }}\
       {${if def:sender_host_addr:from [$sender_host_addr] }}}\
    by $primary_name\n\t\
    ${if def:sender_proto: with $sender_proto }\
    ${if def:ident_sender:(ident $ident_sender using $ident_method) }\
    id $message_id\n\t\
    (Debian $version_string); $spool_date"
');

    $confdescrip=
"Mail generated on this system will have \`$visiblename' used
as the host part (after the \@) in the From: field and similar places.
";
    $confdescrip.= "
Message-ID's, Received lines, etc. will use the system's canonical
hostname, which is currently set to $syshostname.
" if $syshostname ne $visiblename;
    $confdescrip.= "
The following hostname(s) will be recognised as referring to this system:
 ".join(', ',@names)."\n" if $configtype != 3;


    $configtype != 3 && &setfile('aliases',
'# This is the aliases file - it says who gets mail for whom.',
"
postmaster: root
$rootalias
$redirinalias
mailer-daemon: postmaster");


    $confdescrip.="
Mail for postmaster, root, etc. will be sent to ".
(@postmasters ? join(', ',@postmasters) : 'root').".\n" if $configtype != 3;


    $configtype != 3 && &setfile('smail/directors',
'# This is the Smail directors file, which deals with mail for
# local users (ie, mail which is destined for a user of this system).',
'
aliases:
	driver=aliasfile, owner=postmaster, sender_okay;
	file=/etc/aliases, proto=lsearch,
	modemask=002, owners=root:mail:daemon, owngroups=root:mail:daemon

dotforward:
	driver=forwardfile, owner=postmaster, nobody, sender_okay;
	file=~/.forward,
	checkowner, modemask=022, owners=root,
	unsecure=0-99:~ftp:~uucp:/tmp:/var/tmp,

user:
	driver=user;
	transport=local

real_user:
	driver=user;
	transport=local,
	prefix=real-

# lists - expand local mailing lists stored in a list directory
# mailing lists can be created simply by creating a file in the
# /etc/smail/lists directory.  To get local error bounces sent
# to the listowner put their name in /etc/smail/lists/owner-whatever.
lists:
	driver=forwardfile, sender_okay, owner=owner-$user,
        caution, nobody;
	file=lists/${lc:user}
');



     $configtype == 3 && &setfile('smail/directors',
'# This is the Smail directors file, which deals with mail for
# local users.  However, it is configured to send even mail
# which looks local to our smarthost for processing.',
"
smart_user:
	driver=smartuser;
	new_user=\$user\@$smarthost,
	well_formed_only
");


    $confdescrip.= "\nLocal mail is delivered.\n" if $configtype != 3;

     ($configtype == 1 || $configtype == 3) && &setfile('smail/routers',
'# This is the Smail routers file, which says what to do with mail destined for
# remote hosts.  This configuration is for Internet and satellite systems.',
'
'. ($usesmarthost < 3 ? 
'inet_addrs:
	driver=gethostbyaddr, transport=smtp;
	check_for_local, fail_if_error

inet_hosts:
	driver=bind, transport=smtp;
	defer_no_connect, -local_mx_okay, defnames,
':''). ($usesmarthost == 0 ? 
'	gateways=uu.net:uucp:+:cunyvm.cuny.edu:bitnet
':''). ($usesmarthost == 1 ? 
"	gateways=$smarthost:uucp:bitnet
":''). ($usesmarthost == 2 ? 
'	ignore_domains=uucp:bitnet
':''). ($usesmarthost < 3 ? 
'
':''). ($usesmarthost >= 2 ? 
"smart_host:
	driver=smarthost, transport=smtp;
	path=$smarthost

":''));


    $confdescrip.= $configtype == 3 ? "
All mail is sent to $smarthost via SMTP and TCP/IP (using any
MX records in the DNS)." :
                 $configtype == 1 && $usesmarthost == 3 ? "
Outbound remote mail is sent to $smarthost
via SMTP and TCP/IP (using any MX records in the DNS)." :
                 $configtype == 1 && $usesmarthost == 2 ? "
Outbound remote mail is first looked up in the Internet DNS, and delivered
using that data if this yields results.  Messages for which no
entry is found in the DNS are sent to $smarthost
via SMTP and TCP/IP (using any MX records for it in the DNS)." :
                 $configtype == 1 && $usesmarthost == 1 ? "
Outbound remote mail is looked up in the Internet DNS, and delivered
using that data if any is found; otherwise such messages are bounced.
Mail for the non-DNS UUCP and BITNET domains is sent to $smarthost
via SMTP and TCP/IP (using any MX records for it in the DNS)." :
                 $configtype == 1 && $usesmarthost == 0 ? "
Outbound remote mail is looked up in the Internet DNS, and delivered
using that data if any is found; failing that messages are bounced.
Mail for the non-DNS UUCP and BITNET domains are sent to the backbone
sites uu.net and cunyvm.cuny.edu for routing, respectively." :
                 $configtype == 2 ? "
Outbound remote mail is transmitted via batched UUCP to
$smarthost for routing and delivery." :
                 $configtype == 4 ? "
Any mail destined for remote addresses is bounced." : die "internal error";

    $confdescrip.=
"\n\nMail from the system background tasks will be sent to
 root\@$smarthost" if $configtype == 3;


     $configtype == 2 && &setfile('smail/routers',
'# This is the Smail routers file, which says what to do with
# mail destined for remote hosts.  This configuration sends
# all remote mail to your smarthost via UUCP.',
"
smart_host:
	driver=smarthost, transport=uux;
	path=$smarthost
");



    $configtype == 4 && &setfile('smail/routers',
'# This is the Smail routers file, which says what to do with
# mail destined for remote hosts.  However, this configuration
# is for local delivery only, and so has no routing information.
# All mail not recognised as local will be bounced.','');



    &setfile('smail/transports',
'# This is the Smail transports file, which gives details of how
# to actually do the various kinds of delivery specified by the
# directors and routers.',
'# Not all of the following are used by all configurations;
# pipe and file may be called implicitly by Smail when delivering
# to local addresses looking like |... /... ~/... .

local:	driver=appendfile, from, local, inet, return_path, unix_from_hack;
	append_as_user, check_user, file=/var/spool/mail/${lc:strip:user},
	group=mail, mode=0660, notify_comsat, suffix="\n"

smtp:	driver=tcpsmtp, max_addrs=100, -max_chars, inet;
	use_bind, defer_no_connect, -local_mx_okay, defnames

uux:	driver=pipe, uucp, from, max_addrs=5, max_chars=200;
	cmd="/usr/bin/uux - -r $host!rmail $(($user)$)",
	pipe_as_sender, log_output

pipe:	driver=pipe, from, local, inet, return_path, unix_from_hack;
	cmd="/bin/sh -c $user", -ignore_status, -ignore_write_errors,
	log_output, parent_env, pipe_as_user, umask=0077

file:	driver=appendfile, from, local, return_path, unix_from_hack;
	append_as_user, file=$user, expand_user,
	mode=0660, suffix="\n"
');

    do {
        print "\n\nThe following configuration has been entered:

$confdescrip

Is this OK ?  Hit Return or type \`y' to confirm it and install,
or \`n' to make changes (in which case we'll go round again, giving you
your previous answers as defaults.     (y/n) ";

	$!=0; defined($what=<STDIN>) || die "smailconfig: EOF/error on stdin: $!\n";
    } while ($what !~ m/^\s*[yn]?\s*$/i);
    last unless $what =~ m/^n/i;
}

sub setfileshort {
    local ($filename,$value) = @_;
    push(@files,$filename);
    $filecontents{$filename}= $value;
}

sub setfile {
    local ($filename,$value1,$value2,$d) = @_;
    chop($d=`date`);
    $v=
"$value1\
# It was originally generated by `smailconfig', part of the Smail package
# distributed with Debian, but it may edited by the mail system administrator.
# It was originally generated by smailconfig at $d
# Please modify the above line, if you change this file by hand.
# See smailconf(5) for details of the things that can be configured here.
$value2";
    push(@files,$filename);
    $filecontents{$filename}=$v;
}

sub reswarn {
    print STDERR "$_[0]\n";
    return 0;
}

sub query {
    local ($question, $varname, $default, $check, $opts) = @_;
    local ($allowempty, $response, $e);
    print "\n";
    $allowempty= $opts =~ m/e/;
    if (eval "defined(\$$varname)") {
        $default= eval "\$$varname";
        $default='none' if $default eq '' && $allowempty;
    }
    for (;;) {
        print "$question\nEnter value (";
        print "default=\`$default', " if length($default);
        print "\`x' to restart): ";
	$!=0; defined($iread=<STDIN>) || die "smailconfig: EOF/error on stdin: $!\n";
        $_= $iread; s/^\s+//; s/\s+$//;
        return 0 if m/^x$/i;
        $_= $default if $_ eq '';
        if (!length($_)) {
            print "  Sorry, you must enter a value.\n";
            next;
        }
        $_= '' if $_ eq 'none' && $allowempty;
        $response= $_;
        last if eval $check;
        if (length($@)) {
            print STDERR "  Aargh, bug - bug - please report:\n$@\nin\n $check\n";
            last;
        } else {
            print "  Sorry, that value is not acceptable.\n";
        }
    }
    $e= "\$$varname = \$response;";
    eval $e; length($@) && die "aargh - internal error ($e): $@";
    1;
}


for $f (@files) {
    open(N,">$etc/$f.postinstnew") || die "Error creating $etc/$f.postinstnew: $!\n";
    print(N $filecontents{$f}) || die "Error writing $etc/$f.postinstnew: $!\n";
    close(N) || die "Error closing $etc/$f.postinstnew: $!\n";
}

while (defined($f= pop(@files))) {
    rename("$etc/$f.postinstnew","$etc/$f") || die "Error installing $etc/$f: $!\n";
}

if ($inetdconf) {
    open(N,">$etc/inetd.conf.postinstnew") || die "Error creating new inetd.conf: $!\n";
    print(N @inetd) || die "Error writing new inetd.conf: $!\n";
    close(N) || die "Error closing new inetd.conf: $!\n";
    rename("$etc/inetd.conf.postinstnew","$etc/inetd.conf") ||
        die "Error installing new $etc/inetd.conf: $!\n";
    if (open(P,"/var/run/inetd.pid")) {
        $pid=<P>;
        if (open(C,sprintf("/proc/%d/stat",$pid))) {
            $_=<C>;
            if (m/^\d+ \(inetd\)/) { kill(1,$pid); }
            close(C);
        }
        close(P);
    }
}

$?=0; system('crontab','-u','mail',"$etc/smail/crontab");
$? && die "Error setting up crontab: $?/$!\n";

print "
Configuration installed.

";

exec $testmsg, $configtype == 4 ? '--localonly' : '--allowremote';
die "Error running $testmsg: $!\n";
