#!/usr/bin/perl -w
#----------------------------------------------------------------------
# copyright (C) 2002 Mitel Networks Corporation
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 		
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 		
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
# 
# Technical support for this program is available from Mitel Networks 
# Please visit our web site www.mitel.com/sme/ for details.
#----------------------------------------------------------------------

use strict;
use esmith::NetworksDB;
use esmith::ConfigDB;
use esmith::util;
use esmith::templates;

my $peers = "/var/service/smtpfront-qmail/peers";
chdir $peers or die "Couldn't chdir to peers directory";

foreach my $rules (qw(local 0))
{
    processTemplate({
			TEMPLATE_PATH => "$peers/$rules",
		});
}

my $config = esmith::ConfigDB->open or die "Could not open config db.";
my $nets = esmith::NetworksDB->open or die "Could not open Networks db.";

my $gw = $config->get('GatewayIP');

# Make a list of local networks, in prefix format
my %nets =
	map
	{
	    $_ => 1,
	}
	    map
	    {
		esmith::util::computeAllLocalNetworkPrefixes($_->key, $_->prop('Mask'));
	    }
		($nets->get_all_by_prop('type', 'network'));

$nets{'127.0.0.1'} = 1;

opendir(PEERS, '.') or
	die "Cannot read peers directory: $!";

# Now manage a set of symlinks to the "local" instructions file
foreach my $insfile (readdir (PEERS))
{
    next unless -l $insfile;
    if (exists $nets{$insfile})
    {
	# Cross this one off the list so that we don't bother creating it
	delete $nets{$insfile};
    }
    else
    {
	# We no longer need this entry
	unlink "$insfile" or
	    warn "Could not delete dnscache access file $insfile: $!\n";
    }
}
closedir(PEERS);

foreach my $insfile (keys %nets)
{
    symlink "local", $insfile or 
	  die "Cannot add instructions file for $insfile: $!\n";
}

if (defined $gw)
{
    # We have a defined gateway address - make sure that the router doesn't have
    # relay privileges
    my $gw_ip = $gw->value;
    unlink $gw_ip;
    symlink "0", $gw_ip or
	  die "Cannot add instructions file for $gw_ip: $!\n";
}

