#!/bin/sh
#
# chkconfig: - 91 35
# description: Starts and stops the Openstack Glance Registry daemon \
#	       used to provide Image storage.
#
# pidfile: /var/run/glance/glance-registry.pid
# config:  /etc/glance/glance-registry.conf


# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 1
fi

# Avoid using root's TMPDIR
unset TMPDIR

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 1

DAEMON=glance-registry
PIDFILE=/var/run/glance/$DAEMON.pid
LOCKFILE=/var/lock/subsys/$DAEMON
CONFIG=/etc/glance/$DAEMON.conf

RETVAL=0
NAME="Glance Registry"

daemon_status() {
	ps -C $DAEMON -o cmd= | grep -v defunct > /dev/null
	return $?
}

start() {
	daemon_status
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		msg_already_running "$NAME"
		passed
		echo
		return 1
	fi
	mkdir -p /var/run/glance
	start_daemon --user glance --make-pidfile --pidfile $PIDFILE \
		--displayname "$NAME" $DAEMON --config-file $CONFIG
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch $LOCKFILE ||\
		RETVAL=1
	return $RETVAL
}

stop() {
	daemon_status
	RETVAL=$?
	if [ $RETVAL -eq 1 ]; then
		msg_not_running "$NAME"
		passed
		echo
		return 1
	fi
	msg_stopping "$NAME"
	start-stop-daemon --stop --pidfile $PIDFILE > /dev/null
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		success
	else
		failure
	fi
	echo
	[ $RETVAL -eq 0 ] && rm -f $LOCKFILE && rm -f $PIDFILE
	sleep 0.1
	return $RETVAL
}

restart() {
	stop
	start
}

status() {
	daemon_status
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		msg_already_running "$NAME"
	else
		msg_not_running "$NAME"
	fi
	echo
	return $RETVAL
}

# Allow status as non-root.
if [ "$1" = status ]; then
	status $SERVICE "$NAME"
	exit $?
fi

# Check that glance-registry.conf exists.
[ -f $CONFIG ] || exit 6

# Check that we can read from it... so non-root users stop here
[ -r $CONFIG ] || exit 4

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
restart)
	restart
	;;
reload)
	restart
	;;
status)
	status
	;;
condrestart)
	[ -f $LOCKFILE ] && restart || :
	;;
condstop)
	[ -f $LOCKFILE ] && stop || :
	;;
*)
	echo $"Usage: $0 {start|stop|restart|reload|status|condrestart|condstop}"
	exit 2
esac

exit $?
