#!/bin/sh

# This script detect the WAN interface and writes /var/run/interface
# Author: Stephan Linke, Robert Allmeroth

. /etc/sysconfig/rc.conf
. /etc/sysconfig/network.conf

if [ -f /mnt/epdocker/features ]; then
    . /mnt/epdocker/features
fi

##. /proc/fiad/hw-info

if [ "$RENAME_NET_INTERFACE" != "yes" ] ; then
	first_eth_if="lan0"
	second_eth_if="lan1"
else
	first_eth_if="eth0"
	second_eth_if="eth1"
fi

DEFAULT_MAC=`cat /sys/class/net/$first_eth_if/address`
if [ -f /mnt/factory/factorysafedir/USN ] ; then
	# to be automatically assigns and registers a unique SIP user name to Epygi's SIP server by using the MAC address from factory save directory
	DEFAULT_MAC=`cat /mnt/factory/factorysafedir/USN`
fi

. /etc/image_features
write_interfaces_info ()
{
	echo "PHYS_LAN=$first_eth_if"						> /var/run/interfaces
	echo "PHYS_WAN=$WAN_IF"						>> /var/run/interfaces
	echo "VIRT_LAN=$second_eth_if"						>> /var/run/interfaces
	echo "VIRT_WAN=$VIRT_WAN"					>> /var/run/interfaces
	echo "WAN_TYPE=$WAN_TYPE"					>> /var/run/interfaces
	echo "WAN_DEV=$WAN_DEV"						>> /var/run/interfaces
	echo "WAN_PROTOCOL=$WAN_PROTOCOL"			>> /var/run/interfaces
	echo "IPPHONE_PNP=$IPPHONE_PNP"				>> /var/run/interfaces
	echo "IPPHONE_WORKING=$IPPHONE_WORKING"		>> /var/run/interfaces

	# store original MAC addresses
	# just create file for now (before we can understand where to get the original MAC address from)

	touch /tmp/ori_mac_addrs
# check lan0 or eth0
	echo "lan0=$DEFAULT_MAC"						 > /tmp/ori_mac_addrs
}

# eth - ethernet is used
# These values are set only for format compatibility 
# with other products
WAN_TYPE="eth"
WAN_DEV="eth"
WAN_PROTOCOL="eth"

##if [ "$START_PPP" = "true" ] ; then
##	WAN_PROTOCOL="pppoe"
##
##	if [ "$PPP_TYPE" = "pppoa" ] ; then
##		WAN_PROTOCOL="pppoa"
##	fi
##fi

##if [ "$START_PPTP_UPLINK" = "true" ] ; then
##	WAN_PROTOCOL="pptp"
##fi

##VIRT_DEFAULT_EXTERNAL_MAC=$DEFAULT_EXTERNAL_MAC

case "$WAN_PROTOCOL" in
	eth)
		WAN_IF=$first_eth_if
		VIRT_WAN=$first_eth_if

		if [ "$START_PBX_ONLY_MODE" = "true" ] ; then
			IPPHONE_PNP=$first_eth_if
			IPPHONE_WORKING=$first_eth_if
			IPPHONE_WORKING_TEMP=$second_eth_if
			
		else
			IPPHONE_PNP=$second_eth_if
			IPPHONE_WORKING=$second_eth_if
			IPPHONE_WORKING_TEMP=$first_eth_if
		fi

		if [ "$FEATURE_VLAN" = "1" ] ; then 
			if [ "$IPLINES_VLAN_ID" != "" ] ; then
				IPPHONE_WORKING="$IPPHONE_WORKING_TEMP.$IPLINES_VLAN_ID"
				IPPHONE_PNP=$IPPHONE_WORKING_TEMP
			fi
		fi
		;;

##	pppoe)
##		WAN_IF="eth1"
##		VIRT_WAN="ppp0"
##		;;
##	pppoa)
##		WAN_IF=""
##		VIRT_WAN="ppp0"
##		VIRT_DEFAULT_EXTERNAL_MAC=""
##		;;
##	pptp)
##		WAN_IF="eth1"
##		VIRT_WAN="ppp0"
##		;;
esac


case "$1" in
if)
	echo $WAN_IF;
	exit 0;
	;;

type)
	echo $WAN_TYPE;
	exit 0;
	;;

dev|device)
	echo $WAN_DEV;
	exit 0;
	;;

h|help)
	echo "Usage: $0 {if|type|device}"
	exit 0
	;;

esac

write_interfaces_info
