#!/bin/sh
PREFIX=$(expr $0 : "\(/.*\)/bin/$(basename $0)\$") || exit 1

if [ -r $PREFIX/etc/utcount.conf ]; then
	. $PREFIX/etc/utcount.conf
else
	exit 1
fi

ipa_users=$PREFIX/etc/$ipa_users

action=$1 ; username=$2

ipa_add_user ()
{
	username=$1 ; usernum=$2
	printf "rule $ipa_username_prefix$username {\n\tipfw = $usernum\n}\n" \
		>> $ipa_users
	if [ -r /var/run/ipa.pid ] ; then
		kill -HUP `cat /var/run/ipa.pid` >/dev/null 2>&1
		sleep 5
	fi
}

if [ -f $ipa_users ] ; then
	startline=`grep -n "^rule $ipa_username_prefix$username " $ipa_users \
		| awk -F: '{print $1}'`
	if [ $startline ] ; then
		usernum=`head -n $(expr $startline + 1) $ipa_users \
		| tail -n 1 | awk -F= '{print $2}'`
	else
		usernum=`expr $count_startnum + $(wc -l < $ipa_users) / 3 + 1`
		ipa_add_user $username $usernum
	fi
else
	usernum=`expr $count_startnum + 1`
	ipa_add_user $username $usernum
fi

if [ "$action" = "-" ] ; then
	/usr/local/sbin/ipa -k dump >/dev/null 2>&1
fi

echo $usernum
