#!/usr/bin/perl -w
use strict;
use vars qw ( $opt_b $opt_h );
use Getopt::Std;
#use lib qw( @@ LIBDIR@@ );
use lib qw( /usr/share/perl5/vendor_perl/ );
# my $kas=/"/";
use Misc;

$ENV{'PATH'} = '/bin:/usr/bin:/sbin:/usr/sbin';

if ( !getopts ('bh')) {
 $opt_h =1;
}

my $ipchains ="";
my $iptables="";
$ipchains = $sysconfig{'IPCHAINS'} if (defined ($sysconfig{'IPCHAINS'})); #path to ipchains command
$iptables = $sysconfig{'IPTABLES'} if (defined ($sysconfig{'IPTABLES'}));; #path to iptables command
my $forceIPCHAINS= $userconfig {'FORCE_IPCHAINS'}; #if force IPCHAINS using

if ( $opt_h ){
print <<EOM
Program shows filter expresions for LinuxStat
ver 1.1, 2003 by Ryszard Pydo

USAGE: show_filters [options]
Options:
-h		This help
-b		Black & White (no colors)

EOM
;
exit;
}


my $red="\e[01;31m";
my $blue="\e[01;34m";
my $norm="\e[00m";
#my $colored=! $opt_b;


if ( $opt_b) { #without colors
 $red='';
 $blue='';
 $norm='';
}

my @info;

if ( ( ! $forceIPCHAINS) && (-x $iptables) ) {
  #iptables version
 print "Using iptables\n\n";
 @info = `$iptables -L -n -v -x`;
 # my $kas=/"`"
  if ($? > 0) {
   print "Problem with iptables ($iptables): $! \n";
   return;
  }
 ShowInfo (\@info);
 @info = `$iptables -L -n -v -t mangle -x`;
 # my $kas=/"`"
 ShowInfo (\@info,1); #for mangle and MARKs


 } #end iptables
  else
  {
   if ( -x $ipchains ) {
  #ipchains version
  print "Using ipchains\n\n";
 @info = `$ipchains -L -n -v -x`;
 # my $kas=/"`"
  if ($? > 0) {
   print "Problem with ipchains ($ipchains): $! \n";
   return;
  }
 ShowInfo (\@info);
  } #end ipchains
 } #end else


sub ShowInfo {
 my $Refinfo = shift;
 my $mangle = shift;

 $mangle = 0 if (! defined ($mangle));
my $curchain;
my ($curline, $markpos, $mark);


foreach my $line (@$Refinfo) {
 next if ($line =~ /^\s*$/);
 if ($line =~ /^Chain\s+(\S+)/) { #extrct new chain
  $curchain = $1;
  $curchain .= '_M' if ($mangle == 1); #for iptables and mangle
  $curchain .= '_N' if ($mangle == 2); #for iptables and nat
  if ($line =~ /\(policy\s+\w+\:?\s*(\d+)\s+\w+\,\s*(\d+)/) {   #main chain, test it
   $curline=0;
   print ("$red$curchain",$curline++,"$norm  ", $line);
   print '-' x 60,"\n";
  }
   $curline=1;
 }elsif ($line =~ /^\s*pkts/) { #info line
  $markpos = index ($line, 'mark') if ($line =~ /mark/);
  print "Filter  Mark $line";
 } else {  #line with data
  if (defined ($markpos)){
  $mark = substr ($line, $markpos, 10);
  if  ($mark =~/^0x/) {
  #has mark
  $mark =~ s/\s//g;
  $mark = 'm'.hex ($mark);
  } }
  $mark = 'm'.hex ($1) if ($line =~ /MARK set (0x\w+)/); #iptables version
  $mark ='   ' if (! defined ($mark));
  print ("$red$curchain",$curline++,"$blue $mark $norm", $line);
  print '-' x 60,"\n";
  }
}
}
