#!/bin/sh /etc/rc.common

START=60
STOP=05

USE_PROCD=1
PROG=/usr/sbin/dm-service

BBFDM_MICROSERVICE_DIR="/etc/bbfdm/services"

. /usr/share/libubox/jshn.sh

log() {
	echo "${@}"|logger -t bbfdmd.services -p info
}

validate_bbfdm_micro_service_section()
{
	uci_validate_section bbfdm micro_services "micro_services" \
		'enable:bool:true' \
		'enable_core:bool:false'
}

_add_microservice()
{
	local name path loglevel
	local enable enable_core unified_daemon

	# Check enable from micro-service
	path="${1}"
	enable_core="${2}"

	name="$(basename ${path})"
	name="${name//.json}"

	json_load_file "${path}"
	json_select daemon

	json_get_var enable enable 1
	if [ "${enable}" -eq "0" ]; then
		log "datamodel micro-service ${name} not enabled"
		return 0
	fi

	json_get_var unified_daemon unified_daemon 0
	if [ "${unified_daemon}" -eq "1" ]; then
		return 0
	fi

	json_select config
	json_get_var loglevel loglevel 4

	procd_open_instance "${name}"

	procd_set_param command ${PROG}
	procd_append_param command -m "${name}"
	procd_append_param command -l "${loglevel}"

	if [ "${enable_core}" -eq "1" ]; then
		procd_set_param limits core="unlimited"
		procd_set_param stdout 1
		procd_set_param stderr 1
	fi

	procd_set_param respawn
	procd_close_instance "${name}"
}

configure_bbfdm_micro_services()
{
	local enable enable_core

	config_load bbfdm
	validate_bbfdm_micro_service_section || {
		log "Validation of micro_service section failed"
		return 1;
	}

	[ "${enable}" -eq "0" ] && return 0

	if [ -d "${BBFDM_MICROSERVICE_DIR}" ]; then
		FILES="$(ls -1 ${BBFDM_MICROSERVICE_DIR}/*.json)"

		for file in $FILES;
		do
			[ -e "$file" ] || continue

			_add_microservice $file "${enable_core}"
		done
	fi
}

_start_single_service()
{
	local service file

	service="${1}"

	if [ -d "${BBFDM_MICROSERVICE_DIR}" ]; then
		file="$(ls -1 ${BBFDM_MICROSERVICE_DIR}/${service}.json)"
		[ -e "$file" ] || return

		_add_microservice $file "0"
	fi
}

start_service()
{
	if [ -n "${1}" ]; then
		_start_single_service "${1}"
	else
		configure_bbfdm_micro_services
	fi
}
