#
# Copyright (C) 2016 LEDE
#

[ -e /etc/config/ubootenv ] && exit 0

touch /etc/config/ubootenv

. /lib/uboot-envtools.sh
. /lib/functions.sh

board=$(board_name)

ubootenv_mtdinfo () {
	UBOOTENV_PART=$(cat /proc/mtd | grep APPSBLENV)
	mtd_dev=$(echo $UBOOTENV_PART | awk '{print $1}' | sed 's/:$//')
	mtd_size=$(echo $UBOOTENV_PART | awk '{print "0x"$2}')
	mtd_erase=$(echo $UBOOTENV_PART | awk '{print "0x"$3}')
	nor_flash=$(find /sys/bus/spi/devices/*/mtd -name ${mtd_dev})

	if [ -n "$nor_flash" ]; then
		ubootenv_size=$mtd_size
	else
		# size is fixed to 0x40000 in u-boot
		ubootenv_size=0x40000
	fi

	sectors=$(( $ubootenv_size / $mtd_erase ))
	sectors=$(printf "0x%x" $sectors )
	echo /dev/$mtd_dev 0x0 $ubootenv_size $mtd_erase $sectors
}

case "$board" in
alfa-network,ap120c-ac|\
devolo,magic-2-wifi-next|\
edgecore,ecw5211|\
glinet,gl-a1300 |\
glinet,gl-ap1300|\
glinet,gl-b1300|\
glinet,gl-b2200|\
luma,wrtq-329acn|\
netgear,wac510|\
openmesh,a42|\
openmesh,a62|\
pakedge,wr-1|\
plasmacloud,pa1200|\
plasmacloud,pa2200)
	ubootenv_add_uci_config "/dev/mtd5" "0x0" "0x10000" "0x10000"
	;;
aruba,ap-303)
	ubootenv_add_uci_config "/dev/mtd13" "0x0" "0x10000" "0x10000"
	;;
aruba,ap-365)
	ubootenv_add_uci_config "/dev/mtd8" "0x0" "0x10000" "0x10000"
	;;
buffalo,wtr-m2133hp|\
netgear,lbr20)
	ubootenv_add_uci_config "/dev/mtd8" "0x0" "0x40000" "0x20000"
	;;
linksys,ea6350v3)
	ubootenv_add_uci_config "/dev/mtd7" "0x0" "0x20000" "0x20000"
	;;
linksys,ea8300|\
linksys,mr8300)
	ubootenv_add_uci_config "/dev/mtd7" "0x0" "0x40000" "0x20000"
	;;
linksys,whw01)
	ubootenv_add_uci_config "/dev/mtd6" "0x0" "0x40000" "0x10000"
	;;
linksys,whw03)
        ubootenv_add_uci_config "/dev/mmcblk0p11" "0x0" "0x100000"
        ;;
linksys,whw03v2)
	ubootenv_add_uci_config "/dev/mtd6" "0x0" "0x80000" "0x20000"
	;;
zyxel,nbg6617)
	ubootenv_add_uci_config "/dev/mtd6" "0x0" "0x10000" "0x10000"
	;;
esac

config_load ubootenv
config_foreach ubootenv_add_app_config ubootenv

exit 0
