#!/bin/sh
# chkconfig: 2345 29 71
### BEGIN INIT INFO
# Provides:          lldpd
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: LLDP daemon
# Description:       lldpd is a 802.1AB implementation, a L2 network
#                    discovery protocol. It also supports CDP, EDP and
#                    various other protocols.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  29
# X-Timesys-Stop-Number:  71
### END INIT INFO

NAME=lldpd
DAEMONUSER=_lldpd
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS=""
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
CHROOT=/var/run/$NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

stop_service() {
    if [  -r $PIDFILE  -a  ! -z ${PIDFILE}  ]; then
	    PID=`cat ${PIDFILE}`
    fi
    if [  ${PID:=0} -gt 1 -a  ! "X$PID" = "X "  ]; then
	    kill ${PID}
    else
	    echo "Unable to read PID file"
    fi
}

start_service() {

    if [ -z "$(grep ^$DAEMONUSER /etc/passwd 2>/dev/null)" ]; then
        echo "$0: Creating system user and group '$DAEMONUSER' with generic settings.  Review and modify as required."
	addgroup --system $DAEMONUSER >/dev/null 2>&1 || addgroup -S $DAEMONUSER >/dev/null 2>&1 || groupadd -r $DAEMONUSER >/dev/null 2>&1 || addgroup $DAEMONUSER >/dev/null 2>&1
        adduser --ingroup $DAEMONUSER --system $DAEMONUSER >/dev/null 2>&1 || adduser -G $DAEMONUSER -S $DAEMONUSER >/dev/null 2>&1 || useradd -g $DAEMONUSER -r $DAEMONUSER >/dev/null 2>&1 || yes '' | adduser $DAEMONUSER >/dev/null 2>&1
    fi

    mkdir -p $CHROOT

    echo "Starting $NAME: "
    $DAEMON $DAEMON_ARGS

    lldpd_rc=$?
    if [ $lldpd_rc -ne 0 ]; then
            echo "[FAIL]"
	    echo "$0: Error ${lldpd_rc} starting ${NAME}... bailing."
	    exit $lldpd_rc
    fi
    echo "[ OK ]"
}

case $1 in

'start')
    start_service
    ;;

'stop')
    stop_service
    ;;

'restart')
    stop_service
    start_service
    ;;

*)
    echo "Usage: $0 [start|stop|restart]"
    ;;
esac
