#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2010 Firewall Services 
# Daniel Berteaud <daniel@firewall-services.com>
# 
# 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
#----------------------------------------------------------------------

use strict;
use esmith::ConfigDB;
use esmith::NetworksDB;
use esmith::event;

my $db = esmith::NetworksDB->open || die "Couldn't open netwoks db\n";
my $ovpndb = esmith::ConfigDB->open_ro('openvpn-s2s') || die "Couldn't open openvpn-s2s db\n";
my @nets = $db->networks;
my @vpnnets = ();
my $vpnnet;

# buils a list of network used by a VPN daemon
foreach my $vpn ($ovpndb->get_all_by_prop(type=>'server'),
                    $ovpndb->get_all_by_prop(type=>'client')){
    foreach (split(/[;,]/,($vpn->prop('RemoteNetworks') || ''))){
        my ($vpnnet,undef) = split(/\//, $_);
        push @vpnnets, $vpnnet;
    }
    push @vpnnets, $vpn->prop('RemoteIP');
}

foreach my $net (@nets){
    my $key = $net->key;
    my $vpn = $db->get_prop($key,"VPN") || '';

    if ($vpn ne ''){
        unless (grep{ $_ eq $key} @vpnnets){
            $db->set_prop($key, type=>'network-deleted');
            event_signal("network-delete","$key");
            $db->get($key)->delete;
        }
    }
}

