#!/bin/bash
#
# agregistry        Startup script for the Access Grid Registry Peer
#
# chkconfig: - 85 15
# description: Registry Peer for Access Grid 3.xx
#
# config: /etc/default/agregistry.conf


if [ -f /etc/default/agregistry.conf ]; then
        . /etc/default/agregistry.conf
fi

[ -z ${AGREGISTRY_EXE} ] && {
  echo "AGREGISTRY_EXE is not set. Set it in /etc/default/agregistry.conf"
  exit 1
}
[ -z ${AGREGISTRY_OWNER} ] && {
  echo "AGREGISTRY_OWNER is not set. Set it in /etc/default/agregistry.conf"
  exit 1
}
[ -z ${AGREGISTRY_HOME} ] && {
  echo "AGREGISTRY_HOME is not set. Set it in /etc/default/agregistry.conf"
  exit 2
}
[ -z ${PEERLISTURL} ] && {
  echo "PEERLISTURL is not set. Set it in /etc/default/agregistry.conf"
  exit 3
}

# Path to the registry peer script, logs and lock file.
prog=RegistryPeer
rp_stdout_log=${AGREGISTRY_HOME}/.AccessGrid3/Logs/RegistryPeerStdOut.log
rp_stderr_log=${AGREGISTRY_HOME}/.AccessGrid3/Logs/RegistryPeerStdErr.log
lockfile=${AGREGISTRY_LOCKFILE:-/var/lock/agregistry}
RETVAL=0

[ -x ${AGREGISTRY_EXE} ] || {
  echo "${AGREGISTRY_EXE} needs to exist and be executable"
  exit 4
}


start() {
    echo -n "Starting Registry Peer ..."
    cd ${AGREGISTRY_HOME} && su ${AGREGISTRY_OWNER} \
      -c "${AGREGISTRY_EXE} \
      -u ${PEERLISTURL} \
      1>>${rp_stdout_log} \
      2>>${rp_stderr_log}" &
    RETVAL=$?
    [ $RETVAL = 0 ] && touch ${lockfile}
    echo
}

stop() {
	echo -n $"Stopping $prog ... "
	pkill -HUP ${prog}
	RETVAL=$?
	[ $RETVAL = 0 ] && rm -f ${lockfile}
        echo
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	sleep 2
	start
	;;
  *)
	echo $"Usage: $prog {start|stop|restart}"
	exit 1
esac

exit $RETVAL
