#!/bin/sh /etc/rc.common
# Copyright (C) 2015-2019 iopsys Software Solutions AB

START=99
STOP=00

USE_PROCD=1
PROG="/usr/sbin/icwmpd"

. /lib/functions.sh
. /usr/share/libubox/jshn.sh

include /lib/network

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

wait_for_resolvfile() {
	local time=$1
	local tm=1

	local resolvfile="$(uci -q get dhcp.@dnsmasq[0].resolvfile)"
	[ -n "$resolvfile" ] || return

	while [ ! -f "$resolvfile" ]; do
		sleep 1
		[ "$tm" -ge "$time" ] && break
		tm=$((tm+1))
	done
}

copy_cwmp_etc_files_to_varstate() {
	mkdir -p /var/run/icwmpd

	if [ -f /etc/icwmpd/icwmpd_backup_session.xml ]; then
		cp -f /etc/icwmpd/icwmpd_backup_session.xml /var/run/icwmpd/ 2>/dev/null
	fi

	if [ -f /etc/icwmpd/dm_enabled_notify.xml ]; then
		cp -f /etc/icwmpd/dm_enabled_notify /var/run/icwmpd/ 2>/dev/null
	fi
}

copy_cwmp_varstate_files_to_etc() {
	if [ -f /var/run/icwmpd/icwmpd_backup_session.xml ]; then
		cp -f /var/run/icwmpd/icwmpd_backup_session.xml /etc/icwmpd/ 2>/dev/null
	fi

	if [ -f /var/run/icwmpd/dm_enabled_notify.xml ]; then
		cp -f /var/run/icwmpd/dm_enabled_notify /etc/icwmpd/ 2>/dev/null
	fi

	# move the successful custom notify import marker to persistent storage
	if [ -f /var/run/icwmpd/icwmpd_notify_import_marker ]; then
		cp -f /var/run/icwmpd/icwmpd_notify_import_marker /etc/icwmpd/
	fi
}

validate_acs_section()
{
	uci_validate_section cwmp acs "acs" \
		'passwd:string' \
		'periodic_inform_enable:bool' \
		'periodic_inform_interval:uinteger' \
		'periodic_inform_time:string' \
		'url:string' \
		'dhcp_discovery:string' \
		'skip_dhcp_boot_options:bool:0' \
		'dhcp_url:string' \
		'compression:or("GZIP","Deflate","Disabled")' \
		'retry_min_wait_interval:range(1, 65535)' \
		'retry_interval_multiplier:range(1000, 65535)' \
		'ssl_capath:string'

}

validate_cpe_section()
{
	uci_validate_section cwmp cpe "cpe" \
		'interface:string' \
		'default_wan_interface:string' \
		'log_to_console:or("enable","disable")' \
		'log_to_file:or("enable","disable")' \
		'log_severity:or("EMERG", "ALERT", "CRITIC" ,"ERROR", "WARNING", "NOTICE", "INFO", "DEBUG")' \
		'log_file_name:string' \
		'log_max_size:uinteger' \
		'userid:string' \
		'passwd:string' \
		'port:uinteger' \
		'provisioning_code:string:""' \
		'amd_version:range(1, 6)' \
		'instance_mode:or("InstanceNumber","InstanceAlias")' \
		'session_timeout:uinteger' \
		'notification:bool' \
		'exec_download:bool' \
		'periodic_notify_enable:bool' \
		'enable:bool:1' \
		'periodic_notify_interval:uinteger' \
		'fw_upgrade_keep_settings:bool'
}

validate_defaults() {
	local ssl_capath enable url dhcp_url

	config_load cwmp

	validate_acs_section || {
		log "Validation of acs section failed"
		return 1;
	}

	if [ -z "${url}" ] && [ -z "${dhcp_url}" ]; then
		log "No ACS URL is configured"
		return 1
	fi

	ssl_capath="${ssl_capath%/}"
	# Put the cert pem file in keep list
	if [ -d "${ssl_capath}" ] && [ "${ssl_capath}" != "/etc/ssl/certs" ]; then
		if ! grep "*.pem\|*.crt" /lib/upgrade/keep.d/icwmp; then
			echo "${ssl_capath}"'/*.pem' >> /lib/upgrade/keep.d/icwmp
			echo "${ssl_capath}"'/*.crt' >> /lib/upgrade/keep.d/icwmp
		fi
	fi

	validate_cpe_section || {
		log "Validation of cpe section failed"
		return 1;
	}

	if [ "$enable" = "0" ]; then
		log "CWMP service disabled"
		return 1
	fi

	return 0;
}

boot() {
	# Copy backup data so that if it restart latter on, it gets the info
	copy_cwmp_etc_files_to_varstate
	mkdir -p /var/run/icwmpd/
	touch /var/run/icwmpd/cwmp

	start
}

start_service() {

	procd_open_instance icwmp

	validate_defaults || {
		log "Validation of defaults failed"
		procd_close_instance
		return 1;
	}

	procd_set_param command "$PROG"
	procd_append_param command -b

	procd_set_param respawn \
		"${respawn_threshold:-5}" \
		"${respawn_timeout:-10}" "${respawn_retry:-3}"

	procd_close_instance
}

stop_service()
{
	local switch_bank

	copy_cwmp_varstate_files_to_etc
	
	switch_bank=$(uci -q -c /var/state/ get icwmp.cpe.switch_bank)
	if [ -n "$switch_bank" ] && [ "$switch_bank" = "1" ]; then
		[ -x /etc/sysmngr/fwbank ] && /etc/sysmngr/fwbank call copy_config
	fi
}

reload_service() {
	local ret

	log "Reload service $ret"
	ret="0"

	validate_defaults || {
		stop
		start
		return 0;
	}

	ret=$(ubus call service list '{"name":"icwmpd"}' | jsonfilter -qe '@.icwmpd.instances.icwmp.running')
	if [ "$ret" != "true" ]; then
		log "Reloading cwmp service ..."
		stop
		start
		return 0
	fi

	tr069_status="$(ubus -t 1 call tr069 status)"
	ret="$?"
	if [ "$ret" = "7" ]; then
		# ubus timed out may be due to uloop is busy in some task so return
		log "Skipping ubus reload due to ubus timeout"
		return 0
	fi

	status="$(echo "${tr069_status}" | jsonfilter -qe '@.cwmp.status')"
	if [ "$status" = "up" ]; then
		ubus -t 1 call tr069 command '{"command":"reload"}'
	fi
}

service_triggers() {
       procd_add_reload_trigger "cwmp"
}

