#!/bin/sh

. /lib/functions.sh

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

set_vendor_id() {
	local wan="${1}"
	local proto="$(uci -q get network."${wan}".proto)"

	if [ "${proto}" = "dhcp" ]; then
		vendorid="$(uci -q get network."${wan}".vendorid)"
		if [ -z "${vendorid}" ]; then
			uci -q set network."${wan}".vendorid="dslforum.org"
		elif [[ $vendorid != *"dslforum.org"* ]]; then
			uci -q set network."${wan}".vendorid="${vendorid},dslforum.org"
		fi
	fi
}

enable_dhcp_option43() {
	local wan="${1}"

	local reqopts="$(uci -q get network."${wan}".reqopts)"
	local proto="$(uci -q get network."${wan}".proto)"
	local newreqopts=""
	local option43_present=0

	for ropt in $reqopts; do
		case $ropt in
			43) option43_present=1 ;;
			*) ;;
		esac
	done

	if [ ${option43_present} -eq 1 ]; then
		return;
	fi

	newreqopts="$reqopts 43"
	if [ "${proto}" = "dhcp" ]; then
		uci -q set network."${wan}".reqopts="$newreqopts"
	fi
}

regenerate_ssl_link() {
	local cert_dir

	cert_dir="${1%/}"
	if [ -f "${cert_dir}" ]; then
		return 0
	fi

	# do not generate the c_rehash if its system default cert path
	# ca-certificate package already generates c_rehash on compilation
	[ ! -d "${cert_dir}" ] || [ "${cert_dir}" = "/etc/ssl/certs" ] && return 0

	generate_links() {
		local file_type="$1"
		local files="${cert_dir}"/*."${file_type}"
		for cfile in ${files}; do
			if [ -f "${cfile}" ]; then
				rehash="$(openssl x509 -hash -noout -in "${cfile}")"
				if [ ! -f "${cert_dir}/${rehash}.0" ]; then
					log "Generating c_rehash for ${cfile}=>${rehash}.0"
					ln -s "${cfile}" "${cert_dir}/${rehash}.0"
				fi
			fi
		done
	}

	generate_links "pem"
}

configure_dhcp_discovery() {
	local dhcp_discovery wan_interface skip_dhcp_boot_options

	config_load cwmp
	config_get wan_interface cpe default_wan_interface "wan"
	config_get dhcp_discovery acs dhcp_discovery "0"
	config_get skip_dhcp_boot_options acs skip_dhcp_boot_options "0"

	if [ "${dhcp_discovery}" = "enable" ] || [ "${dhcp_discovery}" = "1" ]; then
		if [ "${skip_dhcp_boot_options}" -ne 1 ]; then
			# Set dhcp option 43 if not already configured
			enable_dhcp_option43 "${wan_interface}"
			# Set dhcp option 60
			set_vendor_id "${wan_interface}"
		fi
	fi
}

configure_ssl_path() {
	local ssl_capath

	config_load cwmp
	config_get ssl_capath acs ssl_capath

	if [ -n "${ssl_capath}" ]; then
		regenerate_ssl_link "${ssl_capath}"
	fi
}

configure_dhcp_discovery
configure_ssl_path
