#!/usr/bin/perl -W
#date: 
#ali@ali.dnsalias.com
#use diagnostics;
use strict;
use Carp;
use POSIX qw(strftime);
    my 	($one, $two, $three, $four, $five, $six, $seven, $eight, $nine, $ten);
    my 	($eleven, $twelve, $thirteen, $fourteen, $fifteen); 
    my 	($command, $file_to_open, $pattern,  $time_with_sec, $time_without_sec,
	 @system_answer, $some_ip, @some_ip, $counter, $cmd);

$time_with_sec = strftime "%b %d %H:%M:%S", localtime;
$time_without_sec= strftime "%b %d %H:%M", localtime;

#print "datei with sec: $time_with_sec\n date without sec: $time_without_sec\n";	
	if ($ARGV[0]) { $file_to_open=$ARGV[0];
	}else{
	print "usage: $0 <file to open>  <pattern> \n";
	exit();
	}	
	if ($ARGV[1]) {
	$pattern=$ARGV[1];
        }else{
	print "usage: $0 <file to open>  <pattern>\n";
	exit();
 	}

open(LOG, $file_to_open) or carp "Unable to open logfile:$!\n";
while(<LOG>){

		($one, $two, $three, $four, $five, $six, $seven, $eight, $nine, $ten,
	 	$eleven, $twelve, $thirteen, $fourteen, $fifteen)=split(' ');
		       
		#make the time in the logfile without seconds	
		$three =~ s/(\d+\:\d+)\:\d+/$1/;
		#print "$three\n";
		#Searaching for pattern such as sshd, ftpd etc...
		#
 		if(m/\b$pattern\b/gmi)
 		 	{ 
			 #if the times are the same then go ahead
			if ("$one $two $three" eq "$time_without_sec")
				{
				#fetch the ip from the catched client and set it to the $some_ip variable.
					if(m/(\d+\.\d+\.\d+\.\d+)/gmi)
						{
						my $bla;
						$bla="$1 ";
						$bla= $bla."$1 ";
						my @bla = split (' ', $bla);
						print scalar(@bla) ;	
						#if we set it before
						if ($some_ip)
							{
							if ($some_ip !~ m/$1/)
					 			{
								#print "$some_ip ne $1 \n";
								$some_ip = $some_ip ."$1 ";
								
								}

							}else{
							$some_ip = "$1 ";
							}
						}	

				
				}else{
				#very good debug
				#print "$one $two $three\n";
				}	

			}

	    }
close(LOG);
		
		
		##@##print "$some_ip\n";	
		#generating an array from the some_ip variable (strings)
		if($some_ip){
		my @all_ip= split(' ',$some_ip);
		#print "1:$all_ip[0]\n2:$all_ip[1]\n";	
		for (my $i=0; $i <= $#all_ip;$i++)
		{
		#@system_answer=system ("ping -c1  $all_ip[$i]");
		my $result=&ask_iptablets ($all_ip[$i]);
		
		print "\n$result\n";	
			if ($result != 1)	
			{
			$cmd =`iptables -A INPUT -s $all_ip[$i] -j LOG`
			}	
				
		}
		}
	#system("gzip  $file_to_open;mv $file_to_open.gz $file_to_open-`date +%d_%m_%y`.gz; rcxinetd reload "); 

sub ask_iptablets ()
	{
	my (@system,$system, $ip);
	$ip=$_[0];
	$system=`iptables -L -n -v`;
	#print $system ."\n";
		if ($system =~ m/$ip/igm)
		{
		return 1;
		}else{
		return 0;
		}
	}

