#! /bin/sh

# Provides:          lcrd
# Short-Description: light-weighted container runtime daemon
# Description:       lcrd is a light-weighted container runtime daemon

set -e

# /etc/init.d/lcrd: start and stop the lcrd daemon

DAEMON=/usr/bin/lcrd
LCRD_ENABLE=true
LCRD_OPTS='-s test'
LCRD_DEFAULTS_FILE=/etc/default/lcrd
LCRD_CONFIG_FILE=/etc/isulad/daemon.json
LCRD_PID_FILE=/var/run/lcrd.pid

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

if [ -s $LCRD_DEFAULTS_FILE ]; then
    . $LCRD_DEFAULTS_FILE
    case "x$LCRD_ENABLE" in
	xtrue|xfalse)	;;
	xinetd)		exit 0
			;;
	*)		log_failure_msg "Value of LCRD_ENABLE in $LCRD_DEFAULTS_FILE must be either 'true' or 'false';"
			log_failure_msg "not starting lcrd daemon."
			exit 1
			;;
    esac
fi

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin:/usr/local/bin"

lcrd_start() {
    if [ ! -s "$LCRD_CONFIG_FILE" ]; then
        log_failure_msg "missing or empty config file $LCRD_CONFIG_FILE"
        log_end_msg 1
        exit 0
    fi
    if /usr/bin/nohup $DARMON --pidfile $LCRD_PID_FILE $LCRD_OPTS &
    then
        rc=0
        sleep 1
        if ! kill -0 $(cat $LCRD_PID_FILE) >/dev/null 2>&1; then
            log_failure_msg "lcrd daemon failed to start"
            rc=1
        fi
    else
        rc=1
    fi
    if [ $rc -eq 0 ]; then
        log_end_msg 0
    else
        log_end_msg 1
        rm -f $LCRD_PID_FILE
    fi
} # lcrd_start


case "$1" in
  start)
	if "$LCRD_ENABLE"; then
	    log_daemon_msg "Starting lcrd daemon" "lcrd"
	    if [ -s $LCRD_PID_FILE ] && kill -0 $(cat $LCRD_PID_FILE) >/dev/null 2>&1; then
		log_progress_msg "apparently already running"
		log_end_msg 0
		exit 0
	    fi
            lcrd_start
        else
            if [ -s "$LCRD_CONFIG_FILE" ]; then
                [ "$VERBOSE" != no ] && log_warning_msg "lcrd daemon not enabled in $LCRD_DEFAULTS_FILE, not starting..."
            fi
	fi
	;;
  stop)
	log_daemon_msg "Stopping lcrd daemon" "lcrd"
	kill -INT $(cat $LCRD_PID_FILE) 
	log_end_msg $?
	rm -f $LCRD_PID_FILE
	;;

  reload|force-reload)
	log_warning_msg "Reloading lcrd daemon: not needed, as the daemon"
	log_warning_msg "re-reads the config file whenever a client connects."
	;;

  restart)
	set +e
	if $LCRD_ENABLE; then
	    log_daemon_msg "Restarting lcrd daemon" "lcrd"
	    if [ -s $LCRD_PID_FILE ] && kill -0 $(cat $LCRD_PID_FILE) >/dev/null 2>&1; then
		kill -INT $(cat $LCRD_PID_FILE)
		sleep 1
	    else
		log_warning_msg "lcrd daemon not running, attempting to start."
	    	rm -f $LCRD_PID_FILE
	    fi
            lcrd_start
        else
            if [ -s "$LCRD_CONFIG_FILE" ]; then
                [ "$VERBOSE" != no ] && log_warning_msg "lcrd daemon not enabled in $LCRD_DEFAULTS_FILE, not starting..."
            fi
	fi
	;;

  status)
	status_of_proc -p $LCRD_PID_FILE "$DAEMON" lcrd
	exit $?	# notreached due to set -e
	;;
  *)
	echo "Usage: /etc/init.d/lcrd {start|stop|reload|force-reload|restart|status}"
	exit 1
esac

exit 0
