#!/bin/sh /etc/rc.common
# Copyright (C) 2017-2019 Yousong Zhou

START=99

USE_PROCD=1

pservice_list_cb() {
	local val="$1"; shift
	local param="$1"; shift

	procd_append_param "$param" "$val"
}

pservice_instance() {
	local cfg="$1"

	[ "$disabled" = 0 ] || return 0
	[ -x "$command" ] || {
		echo "$command is not executable" >&2
		return 1
	}

	procd_open_instance "$name"
	procd_set_param command "$command"
	procd_set_param stderr "$stderr"
	procd_set_param stdout "$stdout"
	procd_set_param respawn "$respawn_threshold" "$respawn_timeout" "$respawn_maxfail"
	[ -z "$args" ] || config_list_foreach "$cfg" args pservice_list_cb command
	if [ -n "$env" ]; then
		procd_set_param env
		config_list_foreach "$cfg" env pservice_list_cb env
	fi
	if [ -n "$file" ]; then
		procd_set_param file
		config_list_foreach "$cfg" file pservice_list_cb file
	fi
	procd_close_instance
}

start_service() {
	config_load 'pservice'
	config_foreach validate_pservice_section pservice pservice_instance
}

service_triggers() {
	procd_add_validation validate_pservice_section
}

validate_pservice_section() {
	uci_load_validate pservice pservice "$1" "$2" \
		"disabled:bool:0" \
		"name:string" \
		"env:regex('^[a-zA-Z_][a-zA-Z0-9_]*=.*$')" \
		"command:file" \
		"args:string" \
		"stderr:bool:0" \
		"stdout:bool:0" \
		"respawn_threshold:uinteger:3600" \
		"respawn_timeout:uinteger:5" \
		"respawn_maxfail:uinteger:5" \
		"file:string"
}
