#!/bin/sh

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

check_ptp_mode() {
	local wanport enabled updated

	if [ -f /etc/board.json ]; then
		json_init
		json_load_file /etc/board.json
		json_select network
		json_select wan 2>/dev/null
		json_get_var wanport device
		json_select ..
		json_select ..
		json_cleanup

		if [ -f /etc/bbfdm/services/ponmngr.json ]; then
			json_init
			json_load_file /etc/bbfdm/services/ponmngr.json
			json_select daemon
			json_get_var enabled enable

			if [ "$wanport" = "pon" ]; then
				updated=1
			else
				updated=0
			fi

			# Avoid writing to flash if not necessary, since it might affect wear-leveling
			if [ "$enabled" != "$updated" ]; then
				json_add_string enable "$updated"
				json_select ..
				json_pretty
				json_dump > /etc/bbfdm/services/ponmngr.json
			fi
			json_cleanup
		fi
	fi
}

apply_extra_xpon_config() {
	check_ptp_mode
}

set_serial_number() {
	local vendor_id="$1"
	local vssn="$2"

	# Vendor id is not taken from serial automatically, propagate it as well
	/userfs/bin/omcicfgCmd set vendorId "${vendor_id}"
	/userfs/bin/omcicfgCmd set sn "${vendor_id}${vssn}"
}

set_ploam_password() {
	local passwd="$1"
	local hex="$2"

	if [ -z "$hex" -o "$hex" = "0" ]; then
		/userfs/bin/omcicfgCmd set passwdAscii "${passwd}"
	else
		/userfs/bin/omcicfgCmd set passwdHex "${passwd}"
	fi
}

set_equipment_id() {
	local eqid="$1"

	if [ -z "${eqid}" ]; then
		return
	fi

	/userfs/bin/omcicfgCmd set equipmentId "${eqid}"
}

set_loid_authentication() {
	local loid="$1"
	local loid_pwd="$2"

	[ -z "${loid}" ] && return

	/userfs/bin/omcicfgCmd set loid "${loid}"

	if [ -n "${loid_pwd}" ]; then
		/userfs/bin/omcicfgCmd set loidPasswd "${loid_pwd}"
	fi
}

set_onu_version() {
	local onu_version="$1"

	[ -z "${onu_version}" ] && return

	/userfs/bin/omcicfgCmd set onuVersion "${onu_version}"
}

apply_xpon_uci_config() {
	configure_loid_authentication
	configure_equipment_id
	configure_onu_version
}

init_xpon() {
	check_ptp_mode

	# don't start pon daemons if xpon module is not loaded
	[ -d /sys/module/xpon -o -d /sys/module/xpon_10g ] || return

	procd_open_instance ponmgr_cfg
	procd_set_param command /userfs/bin/ponmgr_cfg
	procd_set_param respawn
	procd_close_instance
	procd_open_instance omci
	procd_set_param command /userfs/bin/omci
	procd_set_param respawn
	procd_close_instance
}

deinit_xpon() {
	return
}
