#! /bin/bash
#
# ifplugd  init.d script
[[ -x /usr/sbin/ifplugd ]] || exit 0
[[ -r /etc/default/ifplugd ]] && . /etc/default/ifplugd


#Functions to do individual actions
startdaemon(){
    # Start the application
    echo -n "Starting ifplugd: "
    CONFS=($(find /etc/ifplugd -name '*.conf'))
    ((i=0))
    logger -p daemon.info "Found ${#CONFS[@]} Configurations"
    while ((i < ${#CONFS[@]})) ; do
        unset ARGS INTERFACE
        . ${CONFS[$i]}
	logger -p daemon.info "Starting Interface ${INTERFACE}"
        ((i++))
        /usr/sbin/start-stop-daemon -Svp /run/ifplugd.${INTERFACE}.pid -a /usr/sbin/ifplugd -- ${ARGS}
    done
    if ((${#CONFS[@]} == 0)) ; then
        /usr/sbin/start-stop-daemon -n ifplugd -Sv -x /usr/sbin/ifplugd -- ${ARGS}
    fi
    echo "done"
}
stopdaemon(){
    echo -n "Stopping ifplugd: "
    PIDS=($(find /run -xdev -name 'ifplugd.*.pid'))
    ((i=0))
    while ((i < ${#PIDS[@]})) ; do
        PF=${PIDS[$i]}
        [[ $PF =~ /ifplugd\.([^.]*)\.pid ]]
        IF=${BASH_REMATCH[1]}
        logger -p user.info "Shutting down interface $IF"
        /usr/sbin/start-stop-daemon -n ifplugd -Kqp $PF
        ((i++))
    done
    echo "done"
}

case "$1" in
  start)
        [[ ${ENABLED} == "yes" ]] || exit 0
	startdaemon
	;;
  stop)
  	stopdaemon
	;;
  restart|force-reload)
	stopdaemon
	sleep 2
	startdaemon
	;;
  *)
	echo "Usage: /etc/init.d/ifplugd { start | stop | restart | force-reload }" >&2
	exit 1
	;;
esac

exit 0