#!/usr/local/bin/perl
# $Id: ppaccesslog.pl,v 1.4 1997/02/04 03:43:58 elkner Exp $

# This tiny script writes a new accesslog file, where all not resolved
# IP addresses are replaced with their FQDN, if possible.

use Socket;

$Version="PreProcess Access.log 1.0";

# Location and name of the decompression program
# (usually '/usr/bin/zcat', '/usr/local/bin/zcat',
# '/usr/bin/gzip -cd' or '/usr/local/bin/gzip -cd')
$Zcat="/usr/local/bin/gzip -cd";
$Gzip="/usr/local/bin/gzip -c";
$LogType='common';

$Resolved=0;
$Unresolved=0;
$AlreadyResolved=0;
$Lines=0;
$Lookup=0;
($sec,$min,$hour) = (localtime(time))[1,2,3];

if ($ARGV[0]) {
    while($LogFile=shift) { 
	&Process; 
    }
}

sub Process {
    if ($LogFile=~m/(\.gz|\.Z)/o) {
	$NewFileName=$LogFile;
	$NewFileName=~s/(.*)\.(gz|Z)$/$1\.new\.gz/;
    	$OldFile="$Zcat $LogFile |" ;
	$NewFile="| $Gzip >$NewFileName";
    }
    else {
	$OldFile=$LogFile;
	$NewFileName="$LogFile.new";
	$NewFile="> $NewFileName";
    }
    die ("Unable to open $LogFile\n$!") if (!(open(LOGFILE,$OldFile)));
    die ("Unable to open $NewFileName\n$!") if (!(open(NEWFILE,$NewFile)));

READ:    while(<LOGFILE>) {
	chop;
	$TotalLines++;
	$line=$_;
	($Host,$Rest) = /^(\S+) (.*)/o;
	if ( $Host =~ m#^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$#o ) { 
	    # Check to see if we already know this one.
	    if (defined($DomainLookupList{$Host})) {
		$name=$DomainLookupList{$Host};
		print NEWFILE "$name $Rest\n";
		next READ;
	    }
	    $Lookup++;
	    $ip = inet_aton $Host;
	    $name = (gethostbyaddr($ip, AF_INET))[0];
	    if (! $name) {
		$Unresolved++;
		$name = $Host;
	    }
	    else {
		$Resolved++;
	    }
	    $DomainLookupList{$Host}=$name;
	    print NEWFILE "$name $Rest\n";
	    next READ;
	}
	else {
	    $AlreadyResolved++;
	    print NEWFILE "$line\n";
	    next READ;
	}
    }
    printf "Start: %d:%d:%d\n",$hour,$min,$sec;
    ($sec,$min,$hour) = (localtime(time))[1,2,3];
    printf "End  : %d:%d:%d\n\n",$hour,$min,$sec;
    print "Resolved hosts    : $Resolved\n";
    print "Not resolved Names: $Unresolved\n";
    print "===============================\n";
    print "Lookups           : $Lookup\n\n";
    print "Already resolved  : $AlreadyResolved\n";
    printf "old unres. entries: %s\n", $TotalLines - $AlreadyResolved;
    print "===============================\n";
    print "Total Lines       : $TotalLines\n";

    close(LOGFILE);
    close(NEWFILE);
    ($atime,$mtime)=(stat($LogFile))[8,9];
    utime $atime,$mtime,"$NewFileName";
}
