#!/bin/sh

# Source function library
. /etc/init.d/functions

I2C=$(ls -d  /sys/bus/i2c/drivers/nau8810/*1a |cut -d/ -f7 |cut -d- -f1)

if [ ! -e /etc/default/usbcdc ];then
	ECM0=172.31.255.192;
	printf "ECM0=\"%s\";\n" ${ECM0} > /etc/default/usbcdc
else
	source /etc/default/usbcdc
fi;

get_i2c() {
        if i2cdetect -a -r -y ${I2C} 0x${1} 0x${1} |tail -8 |cut -c5- |grep ${1} > /dev/null 2>&1;then
                return 0;
        else
                return 1;
        fi;
}

setup_route_cdc() {
	ORIGIFS=${IFS}
	local IFS
	IFS=.
	set -- $*
	IFS=${ORIGIFS}

	NW=$(($4 & 0xFFFC))
	IP=$((${NW} + 1))
	REM=$((${NW} + 2))
	BASE=${1}.${2}.${3}

	/sbin/ip link set up dev ecm0
	#Do not use label dnsmasq does not work
	/sbin/ip addr add ${BASE}.${IP}/30 brd + dev ecm0
	/sbin/ip route add default via ${BASE}.${REM} metric 250

	/sbin/ip rule add prio 50 from ${BASE}.${IP} table 50
	/sbin/ip rule add prio 50 oif ecm0 table 50
	/sbin/ip route add ${BASE}.${NW}/30 proto kernel scope link dev ecm0 src ${BASE}.${IP} metric 250 table 50
	/sbin/ip route add default via ${BASE}.${REM} metric 250 table 50
}

configure_eth() {
	if [ -d /sys/kernel/config/usb_gadget/comb-ns-eth ]; then
        	return 0
	fi

	if get_i2c 50;then
		DEV_SERIAL=$(echo -n 0010;for mac in a b c d e f;do MV=$(i2cget -y ${I2C} 0x50 0xf${mac});echo -n ${MV:2};done)
	elif get_i2c 57;then
		DEV_SERIAL=$(echo -n 0010;for mac in 2 3 4 5 6 7;do MV=$(i2cget -y ${I2C} 0x57 0xf${mac});echo -n ${MV:2};done)
	else
		DEV_SERIAL=$(awk -F: '{printf "0010%s%s%s%s%s%s",$1,$2,$3,$4,$5,$6}' /sys/class/net/ethA/address)
	fi;

	SERIAL="$(grep Serial /proc/cpuinfo | sed 's/Serial\s*: 1000\(\w*\)/\1/')"
	MAC="$(echo ${SERIAL} | sed 's/\(\w\w\)/:\1/g' | cut -b 2-)"
	MAC_HOST="12$(echo ${MAC} | cut -b 3-)"
	MAC_DEV="02$(echo ${MAC} | cut -b 3-)"

	modprobe g_cdc iSerialNumber=${DEV_SERIAL} iProduct="Comb NS Board" iManufacturer="Comb Communications" dev_addr=$MAC_DEV host_addr=$MAC_HOST

	#Add routing table for ecm
	setup_route_cdc ${ECM0}
}

case $1 in
        start)
               configure_eth
        ;;
	restart)
		/sbin/ip link set down dev ecm0 | :
		/sbin/ip -4 addr flush dev ecm0 | :
		/sbin/ip route flush dev ecm0 | :
		/sbin/ip route flush table 50 | :
		while /sbin/ip rule del prio 50 >/dev/null 2>&1;do :;done
		setup_route_cdc ${ECM0}
	;;
	stop)
	;;
esac

exit 0
