#!/bin/sh

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

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

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;
}

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

	ip link set up dev ecm0
	#Do not use label dnsmasq does not work
	ip addr add 192.168.100.2/30 brd + dev ecm0
	ip route add default via 192.168.100.1 metric 250

	#Add routing table for ecm
	ip rule add prio 50 from 192.168.100.2 table 50
	ip rule add prio 50 oif ecm0 table 50
	ip route add 192.168.100.0/30 scope link dev ecm0 src 192.168.100.2 metric 250 table 50
	ip route add default via 192.168.100.1 metric 250 table 50

}

case $1 in
        start)
               configure_eth
        ;;
	stop)
	;;
esac

exit 0
