#!/bin/bash

# Copyright (C) 2014-2015:
#    Gabes Jean, naparuba@gmail.com
#
# This file is part of OpsBro.

### BEGIN INIT INFO
# Provides:          opsbro
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: OpsBro service discovery daemon
# Description:       OpsBro is a service discovery daemon
### END INIT INFO

### Chkconfig Header
# OpsBro        Starts OpsBro daemon
#
# chkconfig: 345 99 01
# description: Start OpsBro daemon

# Reference:
# http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html

#set -xv

NAME="opsbro"


export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
BASE=$(basename $0)


## Default paths:
ETC=/etc/opsbro

export PATH="${PATH:+$PATH:}/usr/sbin:/bin:/sbin"
# Try to set US lang, to allow easy sub command call even on non english system (yes like french system...)
export LANG=en_US.UTF8   2>/dev/null
export LC_ALL=en_US.UTF8 2>/dev/null
# Please python, manage utf8 by default, we are in 2017
export PYTHONIOENCODING=utf8
# Do not lock on print calls
export PYTHONUNBUFFERED="1"
# We do nto want libcurl to go through a proxy by itself, so unset evn variables for this one
unset http_proxy
unset https_proxy


# We try to find the LAST possible Python VERSION
pythonver() {
    versions="2.6 2.7"
    LASTFOUND=""
    # Is there any python here?
    for v in $versions
    do
        which python$v > /dev/null 2>&1
        if [ $? -eq 0 ]
        then
            LASTFOUND="python$v"
        fi
    done
    if [ -z "$LASTFOUND" ]
    then
        # Finaly try to find a default python
        which python > /dev/null 2>&1
        if [ $? -ne 0 ]
        then
            # Beware: maybe it's because which is not exiting itself! (like in docker centos images)
            if [ -f "/usr/bin/python" ]; then
                LASTFOUND="/usr/bin/python"
            else
                echo "No python interpreter found!"
                exit 2
            fi
        else
            echo "python found"
            LASTFOUND=$(which python)
        fi
    fi
    PYTHON=$LASTFOUND
}

# Ok, go search this Python version
pythonver



# default
DEBUG=false

## This permits to overhidde the current values (PATH or things like this)
OPSBRO_DEFAULT_FILE="/etc/default/opsbro"

# Reads configuration variable file if it is present
[ -r "$OPSBRO_DEFAULT_FILE" ] && . "$OPSBRO_DEFAULT_FILE"


usage() {
    cat << END
Usage: $NAME [ -d ] {start|stop|status|restart|reload|force-reload}

 -d  start the daemon in debug mode, only useful with start|restart

END
}

if [ "$1" = "-d" ]; then
    DEBUG="1"
    shift
fi

if [ $# -eq 0 ]; then
    usage >&2
    exit 2
fi

CMD=$1



### This bloc part is for debian and redhat things, because they
### are not able to be ok in the most common part: boot
# cross debian/redhat thing
# To be replaced by LSB functions
# Defined here for distributions that don't define
# log_daemon_msg
log_failure_msg () {
    echo_failure $*
}
log_daemon_msg () {
    echo $@
}
# To be replaced by LSB functions
# Defined here for distributions that don't define
# log_end_msg
log_end_msg () {
    retval=$1
    if [ $retval -eq 0 ]; then
        echo "."
    else
        echo " failed!"
    fi
    return $retval
}
echo_success() {
   log_end_msg 0 $*
}
echo_failure() {
    log_end_msg 1 $*
}
# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Source function library.
[ -f /etc/rc.d/init.d/functions ] && . /etc/rc.d/init.d/functions

[ -f /lib/lsb/init-functions ] && . /lib/lsb/init-functions



################################################

#
# Display status
#
do_status() {
    out=$(opsbro agent info)
    rc=$?
    if [ $rc != 0 ]; then
        echo "$NAME NOT RUNNING (cannot contact unix socket server)"
        return 1
    fi
    echo "$NAME is running"
    return 0
}

#
# starts our modules
#
do_start() {
    [ "$DEBUG" = 1 ] && DEBUGCMD="--debug "$(getdebugfile "$mod")
    output=$(opsbro agent start --daemon $DEBUGCMD 2>&1)
    rc=$?
    
    if [ $rc != 0 ]; then
        echo "FAILED: $output"
        return 1
    fi
    echo "OK"
    return 0
}


#
# stops daemon
#
do_stop() {
    # Maybe it's already stop?
    statusoutput=$(do_status)    
    [ $? -ne 0 ] && {
        echo "$statusoutput"
        return 0
    }
    stopoutput=$(opsbro agent stop)
    echo "OK"
    return 0
}



############################

do_start_() {
    echo  "Starting opsbro"
    status=$(do_status)
    rc=$?
    if [ $rc -eq 0 ]; then
        log_warning_msg "Already running"
        return
    fi
    startoutput=$(do_start)
    rc=$?
    if [ $rc -eq 0 ]; then
        echo_success
    else
        log_failure_msg "$startoutput"	
    fi
    return $rc
}


do_stop_() {
    echo  "Stopping opsbro"
    statusoutput=$(do_status)
    rc=$?
    if [ $rc -ne 0 ]; then
        failuremsg="Couldn't get status of opsbro: $statusoutput"
    else
        stopoutput=$(do_stop 2>&1)
        rc=$?
        [ $rc -ne 0 ] && failuremsg="Couldn't stop opsbro: $stopoutput"
    fi
    if [ $rc -ne 0 ]; then
        log_failure_msg "$failuremsg"
    else
        echo_success
    fi
    return $rc
}

do_restart_() {
    echo "Restarting opsbro"
    stopoutput=$(do_stop)
    startoutput=$(do_start)
    rc=$?
    if [ $rc -eq 0 ]; then
        echo_success
    else
        log_failure_msg "$startoutput"
    fi
    return $rc
}


do_force-reload_() {
    do_restart_
}

do_reload_() {
    mod="$1"
    echo "Reloading opsbro"
    stopoutput=$(do_stop)
    startoutput=$(do_start)
    rc=$?
    if [ $rc -eq 0 ]; then
        echo_success
    else
        log_failure_msg "$startoutput"
    fi
    return $rc
}


do_status_() {
    echo "Checking status of opsbro"
    output=$(do_status)
    rc=$?
    if [ $rc -eq 0 ]; then
        echo_success $output
    else
	log_failure_msg "$output"
    fi

}



############################

do_cmd_on() {
    local return_value    
    action=$1
    do_${action}_ || return_value=1
    return $return_value
}


############################
## Main:

case "$CMD" in
    start|stop|restart|status|force-reload)
        do_cmd_on "$CMD"
        ;;
    check|checkconfig|reload)
        do_cmd_on "$CMD"
        ;;
    *)
        usage >&2
        exit 2
        ;;
esac

