#!/bin/sh
#
# For every N lines input, output one line with the maximum values from those N.
#  -# (or -n #) specifies how many input lines to consolidate into one.
#       The default is one output line per 20 input lines.
# If -s is given, each input line should begin yymmdd and output will be split
#       into separate yymmdd files.
# If -p xxx is given, xxx is prepended to yymmdd filenames.
# If -z is given, when a new yymmdd file is started, the old one is compressed.
# If -g is given, when a new yymmdd file is started, the old one is graphed.
#  -y # if given, is passed to the graphing script.
#
# This is intended to accumulate output from the firewall "stats" script
# into daily files for graphing and/or archiving, something like this:
#
# 	ssh -f root@firewall stats -15 | this_script -20 -p firewall -s -z
#
# Corey Satten, corey @ cac.washington.edu, 3/19/02, version 0.5
#

N=20
P=lfw
S=0
Z=0
G=0
USE="Usage: $0 [-#] [-n #] [-s] [-z] [-g] [-p pfx] [-y #] [file]"

for i in $*; do
    case "$1" in
	-s) S=1; shift;;
	-z) Z=1; shift;;
	-g) G=1; shift;;
	-p) P="$2"; shift;shift;;
	-n) N="$2"; shift;shift;;
	-y) Y="$2"; shift;shift;;
   -[0-9]*) N="-($1)"; shift;;
        -*) echo "$USE" 1>&2;exit 1;;
    esac
done

mawk -W interactive "	# gawk without -W interactive also works but more slowly
    BEGIN {N=$N}
    NF==0 {gap=1; next}
    {
    if (((NR-1) % $N == 0) || gap ) {
	if (gap) {
	    print \"\"; gap = 0; b = \$0;
	    }
	else {
	    b = f[1]; f[1] = \$1
	    for(i=2; i<=NF; ++i) {
		b = b \" \" f[i]
		f[i] = \$i
		}
	    }
	if (NR > 1) {
	    if ($S) {
		date = substr(b, 1, 6)
		if (file && file != \"$P-\" date) {
		    close(file)
		    if ($G) system(\"statsplot -g ${Y+"-y $Y"} \" file)
		    if ($Z) system(\"gzip -9 \" file)
		    }
		file = \"$P-\" date
		print b >> file
		fflush(file)
		}
	    else print b
	    }
	}
    else {
	for(i=1; i<=NF; ++i) {
	    if (f[i]<\$i) f[i] = \$i
	    }
	}
    }" $*
