#!/bin/bash
### BEGIN INIT INFO
# Provides:          invirt-dev
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Invirt development configuration
# Description:       
### END INIT INFO

# Author: Invirt project <invirt@mit.edu>

# Do NOT "set -e"

NAME=invirtibuilder
DESC="the Invirt build daemon"
DAEMON="/usr/bin/$NAME"
PIDFILE="/var/run/$NAME.pid"
GEN_FILES=/srv/repository/conf/distributions

[ -x "$DAEMON" ] || exit 0

. /lib/init/std-init.sh
. /lib/init/gen-files.sh

do_start()
{
    # Return
    #  0 if daemon has been started
    #  1 if daemon was already running
    #  2 if daemon could not be started
    ret=0

    gen_files || ret=2
    for d in db dists lists pool; do
        dir="/srv/repository/$d"
        mkdir -p "$dir"
        chown -R repository:nogroup "$dir"
    done
    reprepro-env export || ret=2

    invirt-build-conf || ret=2

    if [ "$ret" = 0 ]; then
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
	log_daemon_msg "Starting $DESC" "$NAME"
	if daemon --running -n $NAME; then
	    log_daemon_msg "$NAME is already running!"
	    return 1
	fi
	daemon -r -O daemon.info -E daemon.err -n $NAME -U $DAEMON || return 2
    fi
    return $ret
}

do_stop()
{
    # Return
    #   0 if daemon has been stopped
    #   1 if daemon was already stopped
    #   2 if daemon could not be stopped
    #   other if a failure occurred
    log_daemon_msg "Stopping $DESC" "$NAME"
    daemon --stop -n $NAME
    RETVAL="$?"
    [ "$RETVAL" = 2 ] && return 2
    # Many daemons don't delete their pidfiles when they exit.
    # rm -f $PIDFILE
    return "$RETVAL"
}

do_reload()
{
    do_stop
    do_start
}

std_init "$@"
