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

START=60
STOP=21

USE_PROCD=1

IS_CFG_VALID=1

validate_ieee1905_section() {
	uci_validate_section ieee1905 ieee1905 "ieee1905" \
			'enabled:bool:true' \
			'macaddress:or("auto",macaddr)' \
			'registrar:string' \
			'extension:bool:false' \
			'extmodule:list(string)' \

	[ "$?" -ne 0 ] && {
		logger -s -t "ieee1905" "Validation of ieee1905 section failed"
		IS_CFG_VALID=0
		return 1
	}
	return 0
}

validate_ali_section() {
	local section="$1"

	uci_validate_section ieee1905 $section "${1}" \
			'ifname:string' \
			'type:or("bridge",string)'

	[ "$?" -ne 0 ] && {
		logger -s -t "ieee1905" "Validation of al-iface section $section failed"
		IS_CFG_VALID=0
		return 1
	}
	return 0
}

validate_ap_section() {
	local section="$1"

	uci_validate_section ieee1905 $section "${1}" \
			'band:or("2", "5", "60", "6")' \
			'ssid:string' \
			'encryption:or("psk2", "sae-mixed", "sae",
				"psk", "psk-mixed", "none", string)' \
			'key:string' \
			'uuid:string' \
			'manufacturer:string' \
			'model_name:string' \
			'device_name:string' \
			'model_number:string' \
			'serial_number:string' \
			'device_type:string' \
			'os_version:uinteger'

	[ "$?" -ne 0 ] && {
		logger -s -t "ieee1905" "Validation of ap section $section failed"
		IS_CFG_VALID=0
		return 1
	}
	return 0
}

validate_ieee1905_config() {
	IS_CFG_VALID=1

	validate_ieee1905_section &&
		config_foreach validate_ali_section "al-iface" &&
		config_foreach validate_ap_section ap

	[ "$IS_CFG_VALID" -ne 1 ] && {
		logger -s -t "ieee1905" "Validation of ieee1905 UCI file failed"
		return 1
	}
	return 0
}

start_service() {
	config_load "ieee1905"
	validate_ieee1905_config || return 1;

	procd_open_instance
        procd_set_param command "/usr/sbin/ieee1905d" "-o"  "/tmp/ieee1905.log" "-f"
	procd_set_param respawn
	procd_set_param limits core="unlimited"
#	procd_set_param env IEEE1905_LOG_CMDU=1
#	procd_set_param stdout 1
#	procd_set_param stderr 1
	procd_close_instance
}

service_triggers()
{
	procd_add_reload_trigger "ieee1905"
}

reload_service() {
	stop
	start
}
