#!/usr/bin/perl -W

#
# Sync Routing Tables Daemon v0x01 by Jakub Wartak ( vnull@pcnet.com.pl )
# Licensed under GPLv2
#
# Likes to be started before Zebra/Quagga/System scripts.
# 
# ChangeLog:
#	8.12.2004 - initial version ( alpha )
#	

use strict;
use POSIX;
use Proc::Daemon;
use Sys::Syslog;

# path to iproute2's ip utility
my $ip = "/sbin/ip";

# turn on verbose mode? 1=yes 0=no
my $verbose = 1;

my @tables = &get_tables_static; # or &get_tables_autodetect <-- not checked

# if are going to use "get_tables_static" you should write here what routing tables 
# are you going to update 
# ( updates are polled from main routing table aka "main" )
my @copy_to = ( 'idsl1', 'polpak1', 'polpak2' );

###################################
# CONFIGURATION SECTION ENDS HERE #
###################################

openlog("syncrtd", "cons,pid", "daemon");
syslog('info', 'Sync Routing Tables Daemon started');

Proc::Daemon::Init;

$SIG{INT} = \&signal_handler;
$SIG{TERM} = \&signal_handler;

open(R, "$ip monitor route |") or die "Unable to open ip monitor mode: $!\n";

while(<R>) {
	chomp;
	my $line = $_;
	my @l = split;

	if ($line =~ /^Deleted\ /) {
		# ke ?
		next if $line =~ /^Deleted\ local\ / or $line =~ /^Deleted\ broadcast\ /;
		# pomijamy wszelkie zmiany do tablic innych niz "main",
		# defaultowo "ip monitor route" nie dodaje "table costam" jesli jest to "main"
		next if($l[6] eq "table");
		$line =~ s/^Deleted\ //g;
		
		foreach my $table ( @tables ) {
		    syslog('info', "Usuwam \"$line\" z tablicy $table") if $verbose;
		}
	} else {
		next if $line =~ /^local/ or $line =~ /^broadcast/;
		next if ($l[5] eq "table");

		foreach my $table ( @tables ) {
		    syslog('info', "Dodaje \"$line\" do tablicy $table") if $verbose;
		}
	}
}

close R;
closelog();

sub get_tables_static
{
	return @copy_to;
}

sub get_tables_autodetect
{
    my @ret = ();

    open (RPDB, "$ip rule ls |")
		or die "Unable to get routing tables: $!\n";

    while (<RPDB>) {
		chomp;
		my @vals = split;
		if ( $vals[1] eq "from" && $vals[3] eq "lookup" &&  $vals[2] ne "all" ) {
		    push @ret, $vals[4];
		    #print "$vals[4]\n";
		}
    }
    
    close RPDB;
    return @ret;
}


sub signal_handler
{
	close R;
	syslog('info', 'Sync Routing Tables Daemon exiting');
	closelog;
	exit(0);
}
