#!/usr/bin/perl
#
# Author: Peter Keel
# 
# Automates some Mail entries, sendmail.cw and both spam-allow files
# on primary and secondary mailserver. 
#
# Not to be used for domains which are only using mail2 as secondary MX.
#

die "Usage: $0 domain\n"       unless($ARGV[0]);

#
# Set filenames
#
$allowmail="/etc/sendmail/spam.allow.relay.domain";
$allowmail2="/var/adm/spam.allow.domain";
$domain=$ARGV[0];

#
# Get the spam-allow file from the com-server.
#
system ("scp -q com:/etc/mail/spam.allow.domain $allowmail2"); 

#
# Check if already entered.
#
open(ALLOW1,"<$allowmail") || die "Cannot open $allowmail for input\n";
    while (<ALLOW1>){
	(@olddom)=split(' ',$_);
            if ($olddom[0] eq $domain){
    	        $flag='true';
                };
        };
close ALLOW1;
die "Domain already in $allowmail. Check manually\n" unless ($flag ne 'true');

open(ALLOW2,"<$allowmail2") || die "Cannot open $allowmail2 for input\n";
    while (<ALLOW2>){
	(@olddom)=split(' ',$_);
            if ($olddom[0] eq $domain){
    	        $flag='true';
                };
        };
close ALLOW2;
die "Domain already in $allowmail2. Check manually\n" unless ($flag ne 'true');

#
# Put it in. 
#
open(ALLOW1,">>$allowmail") || die "Cannot open $allowmail for ouput\n";
print ALLOW1 "$domain\n"
close ALLOW1;

open(ALLOW2,">>$allowmail2") || die "Cannot open $allowmail2 for ouput\n";
print ALLOW2 "$domain\n"
close ALLOW2;

#
# Copy it over. 
#
system ("scp -q $allowmail2 com:/etc/mail/spam.allow.domain");
system ("scp -q $allowmail2 com2:/etc/sendmail/spam.allow.domain");
#
# Rebuild mailertables.  
# 
system ("/etc/sendmail/rebuild");
system ("ssh com /etc/mail/rebuild");
system ("ssh com2 /etc/sendmail/rebuild");
