#!/bin/bash
#
### BEGIN INIT INFO
# Provides:   calico-node
# Required-Start:    $local_fs $network $syslog
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Calico docker container
# Description:
#   Runs calico as a docker container
### END INIT INFO
set -a

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="Calico-node Docker"
NAME=calico-node
DAEMON={{ bin_dir }}/calicoctl
DAEMON_ARGS=""
DOCKER=$(which docker)
SCRIPTNAME=/etc/init.d/$NAME
DAEMON_USER=root

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

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

# Read configuration variable file if it is present
[ -r /etc/network-environment ] && . /etc/network-environment

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

do_status()
{
    if [ $($DOCKER ps --format "{{.Image}}" | grep -cw 'calico/node') -eq 1 ]; then
        return 0
    else
        return 1
    fi
}

# Function that starts the daemon/service
#
do_start()
{
    do_status
    retval=$?
    if [ $retval -ne 0 ]; then
{% if legacy_calicoctl %}
        ${DAEMON} node --ip=${DEFAULT_IPV4} >>/dev/null && return 0 || return 2
{% else %}
         ${DAEMON} node run --ip=${DEFAULT_IPV4} >>/dev/null && return 0 || return 2
{% endif %}
    else
        return 1
    fi
}

#
# Function that stops the daemon/service
#
do_stop()
{
{% if legacy_calicoctl %}
    ${DAEMON} node stop >> /dev/null || ${DAEMON} node stop --force >> /dev/null
{% else %}
    echo "Current version of ${DAEMON} doesn't support 'node stop' command!"
    return 1
{% endif %}
}


case "$1" in
  start)
        log_daemon_msg "Starting $DESC" "$NAME"
        do_start
        case "$?" in
                0|1) log_end_msg 0 || exit 0 ;;
                2) log_end_msg 1 || exit 1 ;;
        esac
        ;;
  stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        if do_stop; then
            log_end_msg 0
        else
            log_failure_msg "Can't stop calico-node"
            log_end_msg 1
        fi
        ;;
  status)
        if do_status; then
            log_end_msg 0
        else
            log_failure_msg "Calico-node is not running"
            log_end_msg 1
        fi
        ;;

  restart|force-reload)
        log_daemon_msg "Restarting $DESC" "$NAME"
        if do_stop; then
            if do_start; then
                log_end_msg 0
                exit 0
            else
                rc="$?"
            fi
        else
           rc="$?"
        fi
        log_failure_msg "Can't restart Calico-node"
        log_end_msg ${rc}
        ;;
  *)
        echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
        exit 3
        ;;
esac
