#!/bin/sh
#
# Start the network....
#

# Debian ifupdown needs the /run/network lock directory

TOPDIR=/ubi/local/apps/network
TMPDIR=/run/network

mkdir -p /run/network

if [ ! -f $TMPDIR/networks ]; then
	echo "$TMPDIR/networks does not exist"
	exit 1
fi


. $TMPDIR/networks


[ -f $TOPDIR/network_functions ] && . $TOPDIR/network_functions


clear_all()
{

	kill_process "ndis_mobile"
	kill_process "udhcpc"
	kill_process "udhcpd"
	kill_process "hostapd"
	kill_process "wpa_supplicant"


	ip link set eth0 nomaster
	ip link set wlan0 nomaster
	ip link delete br0 

	
	ifconfig eth0	down
	ifconfig wlan0	down

	ifconfig eth0	up
	ifconfig wlan0	up
}

lte_bridge()
{
	ifconfig eth0	0.0.0.0
	ifconfig wlan0	0.0.0.0

	$TOPDIR/if-lte $TMPDIR/ifcfg-lte start
	$TOPDIR/if-wlan $TMPDIR/ifcfg-wlan0-wireless start
	create_bridge br0 wlan0 eth0

	$TOPDIR/if-up $TMPDIR/ifcfg-br0 start	
	dhcpd_server br0
	ifconfig br0:1 192.168.88.206 netmask 255.255.255.0 up
}

lte_ap_wan()
{
	ifconfig eth0	0.0.0.0
	ifconfig wlan0	0.0.0.0

	$TOPDIR/if-lte $TMPDIR/ifcfg-lte start
	$TOPDIR/if-wlan $TMPDIR/ifcfg-wlan0-wireless start

	$TOPDIR/if-up $TMPDIR/ifcfg-wlan0 start	
	$TOPDIR/if-up $TMPDIR/ifcfg-eth0 start	
	$TOPDIR/if-up $TMPDIR/ifcfg-eth0:2 start
	dhcpd_server wlan0
	ifconfig eth0:1 192.168.88.206 netmask 255.255.255.0 up
}

lte_sta_gw()
{
	ifconfig eth0	0.0.0.0
	ifconfig wlan0	0.0.0.0

	$TOPDIR/if-lte $TMPDIR/ifcfg-lte start
	$TOPDIR/if-wlan $TMPDIR/ifcfg-wlan0-wireless start

	$TOPDIR/if-up $TMPDIR/ifcfg-wlan0 start	
	$TOPDIR/if-up $TMPDIR/ifcfg-eth0 start
	$TOPDIR/if-up $TMPDIR/ifcfg-eth0:2 start
	dhcpd_server eth0 
	ifconfig eth0:1 192.168.88.206 netmask 255.255.255.0 up
}

lte_sta_wan()
{
	ifconfig eth0	0.0.0.0
	ifconfig wlan0	0.0.0.0

	$TOPDIR/if-lte $TMPDIR/ifcfg-lte start
	$TOPDIR/if-wlan $TMPDIR/ifcfg-wlan0-wireless start
	$TOPDIR/if-up $TMPDIR/ifcfg-wlan0 start	
	$TOPDIR/if-up $TMPDIR/ifcfg-eth0 start	
	$TOPDIR/if-up $TMPDIR/ifcfg-eth0:2 start
	ifconfig eth0:1 192.168.88.206 netmask 255.255.255.0 up
}

network_start()
{
	echo "charger_work_mode=${charger_work_mode}"
	echo -n > /etc/resolv.conf
	if [ ! -z $DNS1 ]; then
		echo "nameserver $DNS1 # DNS1" >> /etc/resolv.conf
	fi

	if [ ! -z $DNS2 ]; then
		echo "nameserver $DNS2 # DNS2" >> /etc/resolv.conf
	fi




	case "${charger_work_mode}" in
		lte_bridge)
			lte_bridge
			;;
		lte_ap_wan)
			lte_ap_wan
			;;
		lte_sta_gw)
			lte_sta_gw
			;;
		lte_sta_wan)
			lte_sta_wan
			;;
		*)
			echo "unkown network mode!"
			exit 1
			;;
	esac

}



case "$1" in
  start)
 	echo "Starting network..."
	clear_all
	network_start	
	;;
  stop)
	echo -n "Stopping network..."
	clear_all
	;;
  restart|reload)
	echo -n "Restart network..."
	clear_all
	network_start	
	;;
  *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit $?

