#!/bin/bash
#
# consul        Manage the consul-tepmlate
#
# chkconfig:   2345 91 9
# description: Consul Template queries a Consul instance and updates any number
# of specified templates on the filesystem. As an added bonus, Consul Template
# can EXECute arbitrary commands when a template update completes.
#
# processname: consul-template
# config: /etc/consul-template/conf.d
# PIDFILE: /var/run/consul-template.pid

### BEGIN INIT INFO
# Provides:       consul-template
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop:  0 1 6
# Short-Description: Consul Template queries Consul
# Description: Consul Template queries a Consul instance
### END INIT INFO

# source function library
. /etc/rc.d/init.d/functions

PROG="consul-template"
#USER="consul-template"
USER="root"
EXEC="/usr/bin/$PROG"
CONFIGDIR="/etc/consul-template/conf.d"
PIDFILE="/var/run/$PROG/$PROG.pid"
LOCKFILE="/var/lock/subsys/$PROG"
LOGFILE="/var/log/$PROG.log"


# pull in sysconfig settings
[ -e /etc/sysconfig/$PROG ] && . /etc/sysconfig/$PROG

config_chk() {
    $EXEC -config=$CONFIGDIR -log-level=err -once >> $LOGFILE 2>&1
    RETVAL=$?
    if [[ $RETVAL -ne 0 ]]; then
       echo "There was a problem trying to run $PROG, here are last lines of the log file:"
       tail -n 2 $LOGFILE
    fi
    return $RETVAL
}

start() {

    umask 077

    touch $LOGFILE $PIDFILE
    chown $USER:$USER $LOGFILE $PIDFILE
	config_chk || exit 6
    
    echo -n $"Starting $PROG: "

    daemon \
        --pidfile=$PIDFILE \
        --user=$USER \
        " { $EXEC -config=$CONFIGDIR >> $LOGFILE 2>&1 & } ; echo \$! >| $PIDFILE "

    RETVAL=$?
    echo

    [ $RETVAL -eq 0 ] && touch $LOCKFILE

    return $RETVAL
}

stop() {
    pid=`cat "$PIDFILE"`

    echo -n $"Shutting down $PROG: "

    killproc -p $PIDFILE -t 3 $EXEC
    RETVAL=$?

    sleep 1

    echo
    [ $RETVAL -eq 0 ] && rm -f $LOCKFILE2>&1
    return $RETVAL
}

rh_status() {
    status -p "$PIDFILE" -l $PROG $EXEC
}

rh_status_q() {
    rh_status >/dev/null 2>&1
    RETVAL=$?
    return $RETVAL
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading $PROG: "
    kill -HUP $(cat "$PIDFILE")  > /dev/null && success || failure
    RETVAL=$?
    echo
    return $RETVAL
}

case "$1" in
    start)
        rh_status_q && exit 0
	start
        ;;
    stop)
        rh_status_q || exit 0
	stop
        $1
        ;;
    restart)
        stop
	start
        ;;
    reload)
        rh_status_q || exit 7
	reload
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|try-restart|reload|force-reload}"
        exit 2
esac

exit $?


