#! /bin/sh
### BEGIN INIT INFO
# Provides:          registry-auth
# Required-Start:    $network $named $remote_fs $syslog
# Required-Stop:     $network $named $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: registry authentication server
# Description:       Starts Docker registry authentication service.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON="/usr/bin/registry-auth"
DAEMON_OPTS="-logtostderr=true /etc/registry/auth.yml"
LOGFILE="/var/log/registry/auth.log"
NAME="registry-auth"
USER="registry"
DESC="Docker auth server"
PIDFILE="/var/run/${NAME}.pid"

test -x $DAEMON || exit 0

[ -r /etc/default/docker-auth ] && . /etc/default/docker-auth

. /lib/lsb/init-functions

reload_registry_agent() {
	start-stop-daemon --stop --quiet --signal HUP --pidfile $PIDFILE
}

start_registry_agent() {
    start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE \
      --background --startas $DAEMON --user $USER --chuid $USER \
      --no-close -- $DAEMON_OPTS >> $LOGFILE 2>&1
}

stop_registry_agent() {
	start-stop-daemon --stop --retry TERM/10/KILL/5 --quiet --oknodo --pidfile $PIDFILE
}

status_registry_agent() {
	status_of_proc -p "${PIDFILE}" "${DAEMON}" "${NAME}"
}

case "$1" in
    start)
	log_begin_msg "Starting $DESC"
	start_registry_agent
	log_end_msg $?
	;;
    stop)
	log_begin_msg "Stopping $DESC"
	stop_registry_agent
	log_end_msg $?
	;;
    reload)
    	log_begin_msg "Reloading $DESC"
        reload_registry_agent
    	log_end_msg $?
    	;;
    status)
        status_registry_agent
	;;
    restart|force-reload)
	log_begin_msg "Restarting $DESC"
	stop_registry_agent
	start_registry_agent
	log_end_msg $?
	;;
  *)
	echo "Usage: $0 {start|stop|status|restart|force-reload|reload}" >&2
	exit 1
	;;
esac
