#! /bin/sh
#
# $Id: makedat.in,v 1.5 2004/05/09 17:47:04 mrsam Exp $
#
# Copyright 1998 - 2004 Double Precision, Inc.  See COPYING for
# distribution information.
#
# Generic wrapper for makedat.
#
# Usage: makedat.sh -src=src -file=file -tmp=tmpfile -hup=hupfile [ -cidr ]
#
# Create [file] from [src].  [src] can be either a plain text file, or a
# directory. [tmpfile] is used.  if [hupfile] is specified and it exists,
# this file contains a PID, which is SIGHUPed.
#
# -cidr - [src] contains a list of IP netblocks.  Expand entries in [src]
#         that use CIDR or start-end notation using the Net::CIDR Perl
#         module.  Download the Net::CIDR module from
#         http://www.cpan.org/authors/id/M/MR/MRSAM/

prefix="/usr/local";
exec_prefix="${prefix}";

srcfile=""
dstfile=""
tmpfile=""
hupfile=""

usage() {
	echo "Usage: $0 -src=src -file=file -tmp=tmpfile -hup=hupfile [-cidr]" >&2
	exit 1
}

cidr=""

while test $# -gt 0
do
	case $1 in
	-cidr)
		cidr=1
		shift
		;;
	-src=*)
		srcfile=`echo "$1" | sed 's/-src=//'`;
		shift
		;;
	-tmp=*)
		tmpfile=`echo "$1" | sed 's/-tmp=//'`;
		shift
		;;
	-file=*)
		dstfile=`echo "$1" | sed 's/-file=//'`;
		shift
		;;
	-hup=*)
		hupfile=`echo "$1" | sed 's/-hup=//'`;
		shift
		;;
	*)
		usage
		;;
	esac
done

if test "$dstfile" = ""
then
	usage
fi

if test "$srcfile" = ""
then
	usage
fi

if test "$tmpfile" = ""
then
	usage
fi


get_access() {

	if test -d "$srcfile"
	then
		if test "$srcfile" != "CVS"
		then
			for f in "$srcfile"/*
			do
				test -f $f || continue
				cat "$f" || return
			done
		fi
	else
		cat "$srcfile" || return
	fi
	echo "."
}

docidr() {
	if test "$cidr" = 1
	then
		/usr/bin/perl5 -e '
			eval "use Net::CIDR;";

			while (<>)
			{
			    unless ( $Net::CIDR::VERSION &&
			     /^([a-fA-F0-9:\.]+[\-\/][a-fA-F0-9:\.]+)\s+(.*)$/)
			    {
				print;
				next;
			    }

			    my ($net, $line)=($1, $2);

			    foreach ( Net::CIDR::cidr2octets(
					Net::CIDR::range2cidr($net)))
			    {
				print "$_\t$line\n";
			    }
			}
		'
	else
		/bin/cat
	fi
}

get_access | docidr | ${exec_prefix}/bin/makedatprog - "$tmpfile" "$dstfile" || exit 1

if test "$hupfile" != ""
then
	if test -f $hupfile
	then
		kill -HUP `cat "$hupfile"`
	fi
fi
