#!/bin/sh
######################################################################
#
#    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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#
#    Copyright (C) 2009 Network RADIUS SARL <legal@networkradius.com>
#
######################################################################
#
#  This script assumes that "radmin" is in PATH, and that the user
#  running this script has permission to connect to the radmin socket,
#  and to read/write files in the "logdir" directory.  If none of this is
#  true, then it won't work.
#
#   Usage: raddebug [-c condition] [-i client-ip-address] [-I client-ipv6-address] [-f socket_file] [-t timeout]  [-u username]
#
#

usage() {
    printf "Usage: %s: [-c condition] [-d directory] [-n name] [-D dictdir]  [-i client-ip-address] [-I client-ipv6-address] [-f socket_file] [-t timeout] [-u user]\n" $(basename $0) >&2
    exit 2
}

extra=
condition=1
timeout=60
while getopts 'd:n:D:c:i:I:f:t:u:' OPTION
do
  case $OPTION in
  c)	condition="$OPTARG"
	;;
  d)    extra="$extra -d $OPTARG"
	;;
  n)    extra="$extra -n $OPTARG"
	;;
  D)    extra="$extra -D $OPTARG"
	;;
  i)    x="(Net.Src.IP == $OPTARG)"
	if [ "$condition" = "" ]; then
	    condition="$x"
	else
	  condition="$condition && $x"
	fi
	;;
  I)	x="(Net.Src.IP == $OPTARG)"
	if [ "$condition" = "" ]; then
	    condition="$x"
	else
	  condition="$condition && $x"
	fi
	;;
  f)	extra="$extra -f $OPTARG"
	;;
  t)	timeout="$OPTARG"
	[ "$timeout" = "0" ] && timeout=1000000
	;;
  u)	x="(User-Name == '$OPTARG')"
	if [ "$condition" = "" ]; then
	    condition="$x"
	else
	  condition="$condition && $x"
	fi
	;;
  ?)	usage
	;;
  esac
done
shift $(($OPTIND - 1))

radmin="radmin $extra"

#
#  Print the output, and wait for "timeout".  Then, stop printing.
#
exec $radmin -e "debug condition $condition " -e "debug socket on"
