#!/bin/bash

#must setup this key!!
#man nsupdate
NSUPDATE="nsupdate -k /etc/freeradius/keys/Kradius-dns-updates.+157+08981.private"

function usage()
{
	echo "Usage: `basename $0` -u User-Name -t Hint -s Acct-Status-Type -i Framed-IP-Address"
	exit 1
}


while getopts "u:t:s:i:" opt; do
	case "$opt" in
	u) USER_NAME=$OPTARG;;
	t) HINT=$OPTARG;;
	s) ACCT_STATUS_TYPE=$OPTARG;;
	i) FRAMED_IP_ADDRESS=$OPTARG;;
	*) usage;;
	esac;
done


HINT=`echo ${HINT} | tr -d  '"'`
USER_NAME=`echo ${USER_NAME} | tr -d '"'`
ACCT_STATUS_TYPE=`echo ${ACCT_STATUS_TYPE} | tr -d '"'`
FRAMED_IP_ADDRESS=`echo ${FRAMED_IP_ADDRESS} | tr -d '"'` 

if [[ "${USER_NAME}" == "" ]] || 
   [[ "${HINT}" == "" ]] ||
   [[ "${ACCT_STATUS_TYPE}" == "" ]] ||
   [[ "${FRAMED_IP_ADDRESS}" == "" ]]; then exit 1; fi


#make sure you update below list to something that fits your setup!
case "${HINT}" in 
	XXX) DOMAINNAME="xxx.you.net";;
	YYY) DOMAINNAME="yyy.you.net";;
	*)exit 1;;
esac;

USER_NAME="${USER_NAME%%@*}"
DNS_A_REC="${USER_NAME}.${DOMAINNAME}"

DELETE_DNS_A_REC="prereq yxdomain ${DOMAINNAME}\nupdate delete ${DNS_A_REC} A"
ADD_DNS_A_REC="update add ${DNS_A_REC} 300 in A ${FRAMED_IP_ADDRESS}"
TOUCH_DNS_A_REC="prereq nxdomain ${DNS_A_REC}\n"

case "${ACCT_STATUS_TYPE}" in
	Start)
		echo -e "${DELETE_DNS_A_REC}\n${ADD_DNS_A_REC}\nsend" | $NSUPDATE
		;;
	Stop)
	#comment below to leave logged out users in DNS
		echo -e "${DELETE_DNS_A_REC}\nsend" | $NSUPDATE
		;;
	Alive)
	#uncomment below to flood active users in during turnup
	#	echo -e "${TOUCH_DNS_A_REC}\n${ADD_DNS_A_REC}\nsend" | $NSUPDATE
		exit 0;;
	*)
		exit 1;;
esac;
