#! /bin/sh
# chkconfig: 2345 90 05
# description: Blackfire Agent daemon
### BEGIN INIT INFO
# Provides:          blackfire-agent
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Blackfire Agent
# Description: Blackfire Agent daemon
### END INIT INFO

# Author: Blackfire <support@blackfire.io>
#

# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="Blackfire Agent"
NAME="blackfire-agent"
DAEMON=/usr/bin/blackfire
DAEMON_COMMAND=agent:start
SCRIPTNAME=/etc/init.d/$NAME
PIDFILE=/var/run/$NAME.pid

SOURCEDIR="/var/run/blackfire"
USER="blackfire"

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

# set -x

VERBOSE=no

fn_exists() { type $1 2>/dev/null | grep -q 'function'; }

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
# Might be available on some RedHat based system via redhat-lsb-core or initscripts
if [ -f /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
else
    log_failure_msg () {
        if [ -n "${1:-}" ]; then
            log_begin_msg $@ "..."
        fi
        log_end_msg 1 || true
    }
fi

if [ -f /etc/init.d/functions ]; then
    . /etc/init.d/functions
    # compatibility layer for RH based
    # Return LSB status
    status_of_proc () {
        status $1
        return $?
    }
fi

# compatibility layer, mostly for RH based
fn_exists log_use_fancy_output || log_use_fancy_output () {
    TPUT=/usr/bin/tput
    EXPR=/usr/bin/expr
    if  [ -t 1 ] &&
        [ "x${TERM:-}" != "x" ] &&
        [ "x${TERM:-}" != "xdumb" ] &&
        [ -x $TPUT ] && [ -x $EXPR ] &&
        $TPUT hpa 60 >/dev/null 2>&1 &&
        $TPUT setaf 1 >/dev/null 2>&1
    then
        [ -z $FANCYTTY ] && FANCYTTY=1 || true
    else
        FANCYTTY=0
    fi
    case "$FANCYTTY" in
        1|Y|yes|true)   true;;
        *)              false;;
    esac
}
fn_exists log_action_msg || log_action_msg () {
    echo "$@." || true
}
fn_exists log_daemon_msg || log_daemon_msg () {
    if [ -z "${1:-}" ]; then
        return 1
    fi
    if [ -z "${2:-}" ]; then
        /bin/echo -n $"$1:" || true
        return
    fi

    /bin/echo -n $"$1: $2" || true
}
# int log_begin_message (char *message)
fn_exists log_begin_msg || log_begin_msg () {
    if [ -z "${1:-}" ]; then
        return 1
    fi
    /bin/echo -n "$@" || true
}
# int log_end_message (int exitstatus)
fn_exists log_end_msg || log_end_msg () {
    local retval
    retval=$1
    echo
    return $retval
}

log_clear_line()
{
    if log_use_fancy_output; then
        echo -n -e "\r\033[2K"
    else
        echo
    fi
}

create_socket_dir()
{
    if [ ! -d "$SOURCEDIR" ]
    then
        mkdir -p $SOURCEDIR || exit 1
    fi
    chown $USER:$USER $SOURCEDIR || exit 1
    chmod 0755 $SOURCEDIR || exit 1
}

checklist()
{
    create_socket_dir

    if [ "$VERBOSE" != no ]; then
        log_clear_line
        log_action_msg "Checking configuration"
        log_daemon_msg "$1 $DESC" "$NAME"
    fi
    su $USER --shell /bin/sh -c "$DAEMON $DAEMON_COMMAND --test >/dev/null; exit \$?"
    if [ "0" != "$?" ]; then
        if [ "$VERBOSE" != no ]; then
            log_clear_line
            log_failure_msg "configuration is incorrect"
            log_daemon_msg "$1 $DESC" "$NAME"
        fi
        return 1
    fi

    return 0
}

if [ -x /sbin/start-stop-daemon ]; then
    # Debian based systems
    #
    # Function that starts the daemon/service
    #
    do_start()
    {
        checklist $1
        if [ ! $? -eq 0 ]; then
            return 2
        fi

        # Return
        #   0 if daemon has been started
        #   1 if daemon was already running
        #   2 if daemon could not be started
        start-stop-daemon --oknodo -N 19 --chuid $USER --background --start --quiet --exec $DAEMON $DAEMON_COMMAND --test > /dev/null \
                || return 1
        start-stop-daemon --oknodo -N 19 --chuid $USER --background --start --quiet --exec $DAEMON $DAEMON_COMMAND -- \
                || return 2
        # Add code here, if necessary, that waits for the process to be ready
        # to handle requests from services started subsequently which depend
        # on this one.  As a last resort, sleep for some time.
    }

    #
    # Function that stops the daemon/service
    #
    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
        start-stop-daemon --oknodo --stop --quiet --retry=TERM/30/KILL/5 --exec $DAEMON
        RETVAL="$?"
        [ "$RETVAL" = 2 ] && return 2
        # Wait for children to finish too if this is a daemon that forks
        # and if the daemon is only ever run from this initscript.
        # If the above conditions are not satisfied then add some other code
        # that waits for the process to drop all resources that could be
        # needed by services started subsequently.  A last resort is to
        # sleep for some time.
        start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
        [ "$?" = 2 ] && return 2
        # Many daemons don't delete their pidfiles when they exit.
        rm -f $PIDFILE
        return "$RETVAL"
    }
else
    # RH based systems
    #
    # Function that starts the daemon/service
    #
    do_start()
    {
        checklist $1
        if [ ! $? -eq 0 ]; then
            echo_failure
            return 2
        fi

        daemon --user ${USER} --pidfile ${PIDFILE} "${DAEMON} ${DAEMON_COMMAND} > /dev/null 2>&1 &"
        RETVAL=$?
        pid=`pgrep -f ${DAEMON} 2>/dev/null`
        if [ "$RETVAL" = 0 ] && [ -n "$pid" ]; then
            renice 19 -p ${pid} > /dev/null 2>&1
            echo $pid > "${PIDFILE}"
        fi

        return $RETVAL
    }

    do_stop()
    {
        killproc -p ${PIDFILE} "${DAEMON}"
        return $?
    }
fi

case "$1" in
  start)
        log_daemon_msg "Starting $DESC" "$NAME"
        do_start "Starting"
        case "$?" in
                0|1) log_end_msg 0 ;;
                2) log_end_msg 1 ;;
        esac
        ;;
  stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        do_stop
        case "$?" in
                0|1) log_end_msg 0 ;;
                2) log_end_msg 1 ;;
        esac
        ;;
  status)
        status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
        ;;
  restart|force-reload)
        #
        # If the "reload" option is implemented then remove the
        # 'force-reload' alias
        #
        log_daemon_msg "Restarting $DESC" "$NAME"
        do_stop
        case "$?" in
          0|1)
                do_start "Restarting"
                case "$?" in
                        0) log_end_msg 0 ;;
                        1) log_end_msg 1 ;; # Old process is still running
                        *) log_end_msg 1 ;; # Failed to start
                esac
                ;;
          *)
                # Failed to stop
                log_end_msg 1
                ;;
        esac
        ;;
  *)
        echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
        exit 3
        ;;
esac
