#!/usr/bin/perl
# run logres to resolve IP addresses into host name
#  (fully qualified domain names)
# also clean up the log records, truncating very long fields, etc.

if    (-x '/opt/local/bin/logres') {$LOGRES='/opt/local/bin/logres';}
elsif (-x '/usr/local/bin/logres') {$LOGRES='/usr/local/bin/logres';}
else                               {die("can't find logres\n")}

$opt_f='';
$opt_p='';
chop($DA=`which date`);
die("can't find date program\n") if $DA =~ /^no /;

$ostype=&setos();
if ($ostype eq 'solaris') {		# do it the Y2K compatible way
  chop($date=`$DA +%Y%m%d%H`);		# yyyymmddhh
  die("old date program does not support %Y option\n") unless $date;
} else {				# SunOS can't handle %Y
  chop($date=`$DA +19%y%m%d%H`);	#  so fake it with 19%y
}

while ($ARGV[0]) {
    if ($ARGV[0] eq '-f') {
	$opt_f=1;
	shift;
    } elsif ($ARGV[0] eq '-p') {
	$opt_p=1;
	shift;
    } elsif ($ARGV[0] =~ /^\d\d\d\d\d\d\d\d\d\d$/) {
	$date=$ARGV[0];
	shift;
    } else {
	die "usage: daily-logres [yyyymmddhh] [-f] [-p]

-f     overwrite existing output files, if any
-p     log files are in previous week's directory\n";
    }
}


$| = 1;					# unbuffered output
$PRG='/www/data/httpd/pl';
$LOG='/www/data/httpd/log/fu';
$accfil="httpd.access.$date.day";
$weekfile="$PRG/nextweek";		# the week that ends next Saturday
$weekfile="$PRG/thisweek" if $opt_p;	# the week that ends last Saturday

@hostlist = ('jonapot', 'kwaziwai');

if (open(DATEFILE, "<$weekfile")) {
    chop($currwk=<DATEFILE>);
    chop($curr=<DATEFILE>);
    close(DATEFILE);
    print "current week ends $currwk ($curr)\n";
}

chdir("$LOG");
# use logres to resolve IP addresses into host names
# -k means remove the input file after processing
open (CMD, "|$LOGRES -k -c -") || die "Can't open $LOGRES: $!\n";
for $host (@hostlist) {
    my($infile) ="$host/$curr/$accfil.wrk.gz";
    my($outfile)="$host/$curr/$accfil.gz";
    if (!-r $infile) {			# does the log file exist?
	print "$infile is missing!\n";
	next;
    }
    if (-r "$outfile") {
	if ($opt_f) {
	    if (unlink($outfile)) {
		print "removed existing $outfile\n";
	    } else {
		print "unable to remove $outfile: $!\n";
		next;
	    }
	} else {
	    print "$outfile exists, use -f to overwrite\n";
	    next;
	}
    }
    print CMD "resolve $infile $outfile\n";
}
close (CMD);



# find out our OS type
# returns "solaris" or "sunos"
sub setos {
  system("/bin/sun");
  if (!$?) {
    if (substr (`/bin/uname -r`,0,1) >= 5) {
      return 'solaris';
    }
    return 'sunos';
  }
  return '???';
}
