#! /bin/sh
#*+***********************************************************************
#*
#*  Module:
#*	Mental Ray for Maya
#*
#*  Copyright (c) 2003-2003 by Alias Systems, Inc., and Alias,
#*  a division of Silicon Graphics Canada Ltd.  All rights reserved.
#*
#*  This script installs or uninstalls the SPM licence server entry
#*  in ${SERVICES}
#*
#*-***********************************************************************
SERVICES=/etc/services
MSGPREFIX="<-- Do not modify this number. "
SPMMSG="SPM service"
SPMSVC="mi-spm"
SPMPORT="7050/tcp"
ECHO="/bin/echo -e";
PROG=`basename $0`

if test ".$UID" == "." ; then
	UID=`id | awk 'BEGIN{ FS="[=(]" } { print $2}'`
fi
if test "$UID" != "0" ; then
	echo "!!! $PROG must be run with root priveleges";
	exit ;
fi

install_svc () {
	name=$1
	port=$2
	file=$3
	msg=$4
	grep "^${name}[ \t]" ${file} 1>/dev/null 2>&1
	if [ $? != 0 ] ; then
		echo "    adding ${name} entry." ;
		${ECHO} "${name} \\t${port} \\t# 1 ${MSGPREFIX} ${msg}" >> ${file} 
	else
		echo "     ${name} service entry exists";
	    awk "/^${name}[ \t]/ { id=\$4; if(!\$4) id=1; print \$1 \" \t\" \"${port}\" \"\t# \" id+1, \"${MSGPREFIX} ${msg}\"; next} {print}" \
		 ${file} > ${file}.work;
		mv ${file}.work ${file}
	fi	
}

remove_svc() {
	name=$1
	file=$2
	msg=$3
	grep "^${name}[ \t]" ${file} 1>/dev/null 2>&1
	if [ $? = 0 ] ; then
		echo "    Removing ${name} entry." ;
    	awk "/^${name}[ \t]/ { if (\$4-1>0) print \$1 \" \t\" \$2 \"\t# \" \$4-1, \"${MSGPREFIX} ${msg}\"; next } {print}" \
			${file} > ${file}.work ;
		mv ${file}.work ${file}	
	else
		echo "    ${name} entry not found."
	fi
}

case $1 in
	'install')
		echo "    Old ${SERVICES} copied to ${SERVICES}.bak"
		cp ${SERVICES} ${SERVICES}.bak 
		cp ${SERVICES} /tmp/services
		install_svc ${SPMSVC} ${SPMPORT} /tmp/services "${SPMMSG}"
		mv /tmp/services ${SERVICES}
	;;
	'remove')
		echo "    Old ${SERVICES} copied to ${SERVICES}.bak"
		cp ${SERVICES} ${SERVICES}.bak 
		cp ${SERVICES} /tmp/services 
		remove_svc ${SPMSVC} /tmp/services "${SPMMSG}"
		mv /tmp/services ${SERVICES}
	;;
*)
	echo "usage: install_service {install|remove}"
	;;
esac

