#!/bin/sh /etc/rc.common
# Copyright (C) 2015 OpenWrt.org

START=90

get_config() {
	config_get_bool enabled $1 enabled 0
	config_get_bool amend $1 amend 0
	config_get filepath $1 filepath /usr/bin/supervisord
}

start() {
	config_load supervisord
	config_foreach get_config supervisord
	[ $enabled -eq 0 ] && exit 0
	$filepath -c /etc/supervisord/supervisord.conf -d
}

stop() {
	config_load supervisord
	config_foreach get_config supervisord
	$filepath ctl shutdown
}

reload() {
    config_load supervisord
	config_foreach get_config supervisord
	[ $enabled -eq 0 ] && logger -t supervisord disabled to stop && stop && exit 0
    status=$(ps | grep supervisord | grep -v grep | grep -v luci | grep -v init | grep -v version | wc -l)
    [ $status -eq 0 ] && logger -t supervisord unstarted to start && start && exit 0
    if [ $amend -eq 1 ]; then
        logger -t supervisord amend to restart
        stop
        sleep 1
        uci set supervisord.main.amend=0
        uci commit supervisord
        start
    else
        logger -t supervisord fixed to reload
        $filepath ctl reload
    fi
}
