# ipsort.awk
#	Supporting file for ipsort utility from Domtools package.
#
# Copyright (C) 1993-2000 Paul A. Balyoz <pab@domtools.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

BEGIN {
	lines = 0;
}

{
	num = split ($1, f, ".");
	if (num != 4) {
		print "ipsort.awk: error: first col must be IP addr on all recs!" | "cat 1>&2";
		exit;
	}
	lines++;
	IP[lines] = $1;
	line[lines] = $0;
}

# Do the sort and output.

END {
	for (i=1; i<=lines; i++) {
#print "trying i=" i " IP=" IP[i];
		split (IP[i], fi, ".");
		ia = fi[1]+0; ib = fi[2]+0; ic = fi[3]+0; id = fi[4]+0;
		for (j=i+1; j<=lines; j++) {
#print "trying j=" j " IP=" IP[j];
			split (IP[j], fj, ".");
			ja = fj[1]+0; jb = fj[2]+0; jc = fj[3]+0; jd = fj[4]+0;
			if (ja<ia || ja==ia&&(jb<ib || jb==ib&&(jc<ic || jc==ic&&(jd<id)))) {
#print "   j is less than i so swapping";
				tempIP = IP[i];
				templine = line[i];
				IP[i] = IP[j];
				line[i] = line[j];
				IP[j] = tempIP;
				line[j] = templine;
				split (IP[i], fi, ".");
				ia = fi[1]+0; ib = fi[2]+0; ic = fi[3]+0; id = fi[4]+0;
			}
		}
		print line[i];
	}
}
