#!/bin/sh
#
# Startup script for the Adobe Flash Media Admin Server (FMAS)
#
# description:
# processname: fmsadmin

# check user
USERID=`id | sed -e 's/).*//; s/^.*(//;'`
if [ "X$USERID" != "Xroot" ]; then
  echo ""
  echo "ERROR: You must be logged in as root to use this command."
  echo "       If you really need to start the server as non-root please"
  echo "       modify this script."
  echo ""
  exit 1
fi

ulimit -n 64536
ulimit -s 1024

PATH=${PATH}:/usr/bin
export PATH

# Path to FCAS binary, and short-form for messages.
INSTALLDIR=`dirname $0`
prog="Adobe Flash Media Admin Server"
adminserver=fmsadmin
RETVAL=0
NLSPATH=./tcSrvMsg:$NLSPATH; export NLSPATH


# setup tmp dir; check if env var is set, otherwise use install dir
tmpdir=${FMS_TMP_DIR}
if [ "$tmpdir" = "" ]; then
  # tmpdir is empty, so use install dir
  tmpdir=$INSTALLDIR"/tmp"
fi

# if tmpdir doesn't end in a slash, add one
lastchar=${tmpdir:${#tmpdir}-1:1}
if [ "$lastchar" != "/" ]; then
  tmpdir=$tmpdir"/"
fi

# check if dir exists; create if necessary
if [ ! -e $tmpdir ]; then
  mkdir -p $tmpdir
fi

# change permissions to make it rwx for everyone
chmod -R 777 $tmpdir

# make sure only one script (server or adminserver) is running at a time
lockname=$tmpdir"script.lck"
displayCount=0
while [ 1 ]
  do
    if mkdir "$lockname" > /dev/null 2>&1
    then
      trap 'rmdir "$lockname"' 0
      trap "exit 2" 1 2 3 15
      break
    else
        if [ $displayCount -eq 0 ]; then
          echo "Waiting for another script to finish..."
        fi
      let displayCount=displayCount+1
      sleep 1
    fi
  done

start() {
        echo "Starting $prog (please check /var/log/messages)"
	pushd $PWD > /dev/null 2>&1
        cd $INSTALLDIR
        export LD_LIBRARY_PATH=".${LD_LIBRARY_PATH:+:}$LD_LIBRARY_PATH"
        nohup ./$adminserver -console -conf ./conf/Server.xml > /dev/null 2>&1 &
        RETVAL=$?
        echo
	popd > /dev/null 2>&1
        return $RETVAL
}
stop() {
        echo "Stopping $prog (please check /var/log/messages)"
	pushd $PWD > /dev/null 2>&1
        cd $INSTALLDIR
        os="`uname -s`"
        if [ "x$os" = "xLinux" ]; then
          killall -s TERM $adminserver
	else
          pkill -TERM -x $adminserver
	fi

	count=60
	stopped=0
	while [ $count -gt 0 ] && [ $stopped -eq 0 ]
	do
		if [ ! -f ./fmsadmin.pid ]; then
			stopped=1
		else
			let count=count-1;
			sleep 1
		fi
	done

	if [ ! -f ./fmsadmin.pid ]; then
		echo "Admin Server has shutdown..."
	else
		killall -s KILL fmsadmin
	fi
	#remove unused shared memory
	./shmrd
        RETVAL=$?
        echo
	popd > /dev/null 2>&1
	return $RETVAL
}

# See how we were called.
case "$1" in
  start)
        start
	sleep 5
        ;;
  stop)
        stop
        ;;
  restart)
        stop
	sleep 6
        start
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $RETVAL
