#!/usr/bin/perl -w
#
# Module: showvrrp
# 
# **** License ****
# Version: VPL 1.0
# 
# The contents of this file are subject to the Vyatta Public License
# Version 1.0 ("License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.vyatta.com/vpl
# 
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
# 
# This code was originally developed by Vyatta, Inc.
# Portions created by Vyatta are Copyright (C) 2005, 2006, 2007 Vyatta, Inc.
# All Rights Reserved.
# 
# Author: Stig Thormodsrud
# Date: 2007
# Description: display vrrp info
# 
# **** End License ****
# 
use strict;
use warnings;

my $log_dir = '/var/log/vrrpd';
my $pid_dir = '/var/run';

sub echo_file {
    my ($file) = @_;

    my @lines = ();
    if (!(-e $file)) {
	return @lines;
    }
    open(my $FH, '<', $file) or die "Unable to open [$file]\n";
    @lines=<$FH>;
    close($FH);
    return @lines;
}

my $intf = "eth";
if ($#ARGV > -1) {
    $intf = $ARGV[0];
}
#
# xorp currently only support eth0-9. if allowed eth10 then the
# sort below wouldn't be sufficient (i.e eth1 eth10 eth2).
#
open(my $LS, "ls $log_dir |grep '^vrrpd_$intf.*\.log\$' | sort |");
while (my $log_file = <$LS>) {
    chomp $log_file;
    #
    # verify that the vrrpd process is still running
    #
    my $pidfile = $log_file;
    $pidfile =~ s/log$/pid/;
    my @lines = echo_file("$pid_dir/$pidfile");
    if (@lines && $lines[0] =~ /^(\d+)$/) {
	my $pid = $1;
	my $ps  = undef;
	$ps = `ps -p $pid -o comm=`;
	if (!defined($ps) || $ps eq "") {
	    $log_file =~ m/^vrrpd_(.*)\.log$/;
	    my $intf_group = $1;
	    print "vrrpd for $intf_group is no longer running\n\n";
	    next;
	}
    }
    print &echo_file("$log_dir/$log_file"), "\n";
}
close($LS);

#end of file
