#!/bin/sh
#
# bcfg-server - Bcfg2 configuration daemon
#
# chkconfig: 2345 19 81
# description: bcfg2 server for configuration requests
#
### BEGIN INIT INFO
# Provides:          bcfg2-server
# Required-Start:    $network $remote_fs $named $syslog
# Required-Stop:     $network $remote_fs $named $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Configuration management Server
# Description:       The server component of the Bcfg2 configuration management
#                    system
### END INIT INFO

# Include lsb functions
test -f "/lib/lsb/init-functions" && . /lib/lsb/init-functions  # debian
test -f "/etc/init.d/functions" && . /etc/init.d/functions  # redhat

# Commonly used stuff
DAEMON=/usr/sbin/bcfg2-server
PIDFILE=/var/run/bcfg2-server/bcfg2-server.pid
PARAMS="-D $PIDFILE"

# Disabled per default
BCFG2_SERVER_OPTIONS=""
BCFG2_SERVER_ENABLED=0

# Include default startup configuration if exists
test -f "/etc/default/bcfg2-server" && . /etc/default/bcfg2-server

if [ "$BCFG2_SERVER_ENABLED" -eq 0 ] ; then
     log_failure_msg "bcfg2-server is disabled - see /etc/default/bcfg2-server"
     exit 0
fi

# Exit if $DAEMON doesn't exist and is not executable
test -x $DAEMON || exit 5

# Internal variables
BINARY=$(basename $DAEMON)
RETVAL=0

start () {
    echo -n "Starting Configuration Management Server: "
    start_daemon ${DAEMON} ${PARAMS} ${BCFG2_SERVER_OPTIONS}
    STATUS=$?
    if [ "$STATUS" = 0 ]
    then
        log_success_msg "bcfg2-server"
        test -d /var/lock/subsys && touch /var/lock/subsys/bcfg2-server
    else
        log_failure_msg "bcfg2-server"
    fi
    return $STATUS
}

stop () {
    echo -n "Stopping Configuration Management Server: "
    killproc -p $PIDFILE ${BINARY}
    STATUS=$?
    if [ "$STATUS" = 0 ]; then
      log_success_msg "bcfg2-server"
      test -d /var/lock/subsys && touch /var/lock/subsys/bcfg2-server
    else
      log_failure_msg "bcfg2-server"
    fi
    return $STATUS
}

status () {
    # Inspired by redhat /etc/init.d/functions status() call
    PID=$(pidof -x $BINARY -o %PPID)
    if [ -n "$PID" ]; then
      echo "$BINARY (pid $PID) is running..."
      return 0
    fi

    if [ -f $PIDFILE ]; then
      if [ -n "$PID" ]; then
        log_failure_msg "$BINARY dead but pid file exists..."
        return 1
      fi
    fi

    log_failure_msg "$BINARY is not running"
    return 3
}

case "$1" in
    start)
        start
        RETVAL=$?
    ;;
    stop)
        stop
        RETVAL=$?
    ;;
    status)
        status
        RETVAL=$?
    ;;
    restart|reload|force-reload)
        stop
        sleep 5
        start
        RETVAL=$?
    ;;
    *)
        log_success_msg "Usage: $0 {start|stop|status|reload|restart|force-reload}"
        RETVAL=1
    ;;
esac

exit $RETVAL
