#!/bin/sh
#
# chkconfig: 2345 98 98
# description: Start the SysMan Authentication daemon

. /etc/sysconfig/ams
export JAVA_HOME

# Check if JAVA_HOME is correctly set.
if [ ! -r "$JAVA_HOME"/bin/java ]; then
  echo "The JAVA_HOME environment variable is not defined correctly."
  echo "Please edit /etc/sysconfig/ams and set JAVA_HOME correctly."
  exit 0
fi

GetSmauthPid()
{
	/bin/ps --cols 200 -A -o pid,ppid,cmd | /bin/grep -i java | /bin/grep -i authentication $* | while read pid ppid command args
	do
		if [ "$ppid" = "1" -a "$args" = "-classic -mx2m authentication.server.AuthenticationServer" ]
		then
			echo "$pid"
			exit
		fi
	done
}

case "$1" in
'start')
       Pid=`GetSmauthPid`
       if [ ! -z "$Pid" ] ; then
           echo "SysMan authentication server already running."
       else
           if [ ! -f /usr/sbin/smauthd ]
           then
                # if there is no smauthd file, exit with error
                echo "/usr/sbin/smauth not found: SysMan authentication server failed to start"
                exit 1
           fi

           # start smauthd now
           LD_PRELOAD=/usr/lib/libpam.so /usr/sbin/smauthd

           /bin/sleep 10
           Pid=`GetSmauthPid`
           if [ ! -z "$Pid" ]; then
               echo "SysMan authentication server (smauthd) started"
           else
              echo "SysMan authentication server (smauthd) failed to start"
              exit 1
           fi
       fi
       ;;
'stop')
        Pid=`GetSmauthPid`
        if [ "X$Pid" != "X" ]
        then
                /bin/kill $Pid
        fi
	echo "SysMan authentication server stopped"
        ;;
'restart')
	/etc/init.d/smauth stop
	/etc/init.d/smauth start
	;;
*)
        echo "usage: $0 {start|stop|restart}"
        ;;
esac

