#!/bin/sh


configure_serial_number() {
	# check if serial number is present in the production data
	local production_sn="$(fw_printenv -n gponsn)"
	if [ ${#production_sn} -eq 12 ]; then
		uci set xpon.ani.serial_number="${production_sn}"
	else
		local macaddr="$(fw_printenv -n ethaddr | tr -d ':' | tr 'a-z' 'A-Z')"
		local vendor_id="IOPS"
		local vssn="${macaddr:4:8}"

		uci set xpon.ani.serial_number="${vendor_id}${vssn}"
	fi
}

configure_ploam_password() {
	# check if PLOAM password is present in the production data
	local passwd="$(uci -q get xpon.ani.ploam_password)"

	if [ -z "${passwd}" ]; then
		local production_passwd="$(fw_printenv -n gponpswd)"
		if [ -n ${#production_passwd} ]; then
			uci set xpon.ani.ploam_password="${production_passwd}"
			uci set xpon.ani.ploam_hexadecimalpassword=0
		fi
	fi
}

configure_loid_authentication() {
	local production_loid
	local production_loidpwd

	local loid="$(uci -q get xpon.ani.loid)"
	local loidpwd="$(uci -q get xpon.ani.loid_password)"

	if [ -z "${loid}" ]; then
		production_loid="$(fw_printenv -n gponloid)"
	fi
	if [ -z "${loidpwd}" ]; then
		production_loidpwd="$(fw_printenv -n gponloid_password)"
	fi

	if [ -n "${production_loid}" ]; then
		uci set xpon.ani.loid="${production_loid}"
	fi
	if [ -n "${production_loidpwd}" ]; then
		uci set xpon.ani.loid_password="${production_loidpwd}"
	fi

}

if [ -s "/etc/config/xpon" ]; then
	if uci -q get xpon.ani >/dev/null; then
		# generate serial number in case its not present and return
		SERIAL_NUMBER="$(uci -q get xpon.ani.serial_number)"
		if [ ${#SERIAL_NUMBER} -ne 12 ]; then
			configure_serial_number
		fi
		configure_ploam_password
		configure_loid_authentication
		exit
	else
		rm -f /etc/config/xpon
	fi
fi
touch /etc/config/xpon

uci set xpon.ani=ani
uci set xpon.ani.enable="1"
configure_serial_number
configure_ploam_password
configure_loid_authentication

