#! /bin/sh

PROGNAME=$0
prefix=/usr/local

err() {
	echo $* >&2
}

usage() {
	echo "$PROGNAME: Convert GNU radius config file to version 0.96 format"
	echo "usage: $PROGNAME [--prefix=PATH][--raddb=PATH]"
	echo
	echo "Options:"
	echo "  --prefix PATH   Set the install prefix you have used when"
	echo "                  configuring your previous installation of"
	echo "                  GNU radius [default: $prefix]"
	echo "  --raddb PATH    Specify the full path to the radius"
	echo "                  configuration directory"
	echo "                  [default: deduced from your previous"
	echo "                   installation]"
}

while [ $# -gt 0 ]; do
	case $1 in
	--prefix|--prefi|--pref|--pre|--pr|--p)
		prefix=$2
		shift 2;;
	--raddb-path|--raddb-pat|--raddb-pa|--raddb-p|--raddb-|--raddb|--radd|--rad|--ra|--r)
		RADDB=$2
		shift 2;;
	--help|--hel|--he|--h)
		usage
		exit 0;;
	*)	err "Invalid switch $1. Try $PROGNAME --help for more info" 
		exit 1;;
	esac
done

if [ ! -x ${prefix}/sbin/radiusd ]; then
	err "Cannot find previous installation of radius under $prefix"
	exit 1
fi
if [ x$RADDB = x ]; then
	# NOTE: This heuristics won't work for versions prior to 0.94
	RADDB=`${prefix}/sbin/radiusd -v 2>&1 | sed -n 's, *configuration directory: *\(/.*\),\1,p'`
	if [ x$RADDB = x ]; then
		err "Cannot deduce configuration directory."
		err "Please use --raddb-path switch"
		exit 1
	fi
fi

if [ x$TMPDIR = x ]; then
	TMPDIR=/tmp
fi
TMP=config.conv.$$
if [ -d $TMPDIR ]; then
	TMP=$TMPDIR/$TMP
fi

trap 'rm -f $TMP' 1 3 15

CONFIG=$RADDB/config

awk -f `dirname $PROGNAME`/config-conv.awk $CONFIG > $TMP

if [ ! -s $TMP ]; then
	err "cannot create output file"
	exit 1
fi

mv $CONFIG ${CONFIG}~
mv $TMP $CONFIG
exit 0
