#!/bin/sh
# wanrouter	WANPIPE WAN Router Initialization Script.
#
# copyright	(c) 1999-2002, Sangoma Technologies Inc.
#
#		This program is free software; you can redistribute it and/or
#		modify it under the terms of the GNU General Public License
#		as published by the Free Software Foundation; either version
#		2 of the License, or (at your option) any later version.
# ============================================================================
# Mar 12, 2001  Nenad Corbic	Added new if support
# Feb 20, 2001  Nenad Corbic	Use /proc/net/wanrouter/status to determine
#				the active devices.
# Jul 17, 2000  Nenad Corbic	Added version option.
#				Fixed the shutdown bug. If all interfaces
#                               are down but modules loaded, unload
#                               modules.
# May 30, 2000  Nenad Corbic    Updated for v2.1.4
#                               Enable IP Forwarding Option	
# Apr 05, 2000  Nenad Corbic 	Updated for v2.1.3
# Feb 22. 2000  Nenad Corbic    Updated for v2.1.2 
# Feb 15, 2000  Nenad Corbic    Load WANPIPE socket module along
#                               with router modules.
# Jan 18, 2000  Nenad Corbic    No interface files are needed for API,
#                               interfaces. No IP addresses neccessary. 
# Nov 09, 1999  Nenad Corbic    Updated for v2.1.1
#                               Enabled starting and stoping
#                               each wanpipe device separately.
# Nov 09, 1999  Nenad Corbic    Updated for v2.1.1
# Oct 04, 1999  Nenad Corbic    Updated for v2.1.0
# Aug 04, 1999  Nenad Corbic    Updated for v2.0.5
# Oct 15, 1998	Jaspreet Singh	Updated for v2.0.4
# Dec 09, 1997	Jaspreet Singh	Updated for v2.0.2
# Nov 28, 1997	Jaspreet Singh	Updated for v2.0.1
# Nov 06, 1997	Jaspreet Singh	Updated for v2.0.0
# Jul 28, 1997	Jaspreet Singh	Updated for v1.0.5
# Jul 10, 1997	Jaspreet Singh	Updated for v1.0.4
# Dec 15, 1996	Gene Kozin	Initial version based on Sangoma's WANPIPE(tm)
# ============================================================================

####### FUNCTION DEFINITIONS #################################################


check_bash ()
{
	BASH_SUPPORT=`echo $BASH_VERSION | cut -d'.' -f1 2> /dev/null`
}

check_awk ()
{
	eval "awk -W version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		AWK_SUPPORT=YES
	else
		AWK_SUPPORT=NO
	fi
}

function cleanup ()
{
	eval "rm -f $WAN_LOCK 2> /dev/null > /dev/null"
	exit $1
}


# ----------------------------------------------------------------------------
# Check to see if a value belongs to the list.
# Return:	0 - yes
#		1 - no
# ----------------------------------------------------------------------------
check_list()
{
	[ $# -lt 2 ] && return 1

	val=$1
	shift
	for i in $*
	do [ "$val" = "$i" ] && return 0
	done
	return 1
}

# ----------------------------------------------------------------------------
# Display error message.
# ----------------------------------------------------------------------------
error() {
	echo -e "$SCRIPT: $*!"
	[ -f "$ROUTER_LOG" ] && echo -e "$*!" >> $ROUTER_LOG
	return 0
}

# ----------------------------------------------------------------------------
# Configure network interface.
# This routine performs TCP/IP-level interface configuration.  Interface name
# is given as an argument. It reads a configuration file with the same name in
# and calls ifconfig and route to do the job.
#
# Configuration file is actually a shell script containing only variables:
#
#	ONBOOT=yes			if not 'yes' then skip this file
#	IPADDR=xxx.xxx.xxx.xxx		IP address of this interface
#	NETMASK=xxx.xxx.xxx.xxx		Network mask for this interface
#	NETWORK=xxx.xxx.xxx.xxx		Network address
#	BROADCAST=xxx.xxx.xxx.xxx	Broadcast address
#	POINTOPOINT=xxx.xxx.xxx.xxx	Point-to-point address
#	GATEWAY=xxx.xxx.xxx.xxx		Gateway address
# ----------------------------------------------------------------------------
interface_up()
{
	ONBOOT=
	IPADDR=
	NETMASK=
	NETWORK=
	BROADCAST=
	POINTOPOINT=
	GATEWAY=

	if [ $NEW_IF_TYPE = YES ]; then
		if [ $LINUX_DISTR = redhat ]; then
			if [ $WANPIPE_INTR_DIR = "/etc/sysconfig/network-scripts" ]; then
				ifup $1
				return 0
			fi
		fi
		source $WANPIPE_INTR_DIR/ifcfg-$1
	else
		source $WANPIPE_INTR_DIR/$1
	fi

	# Configure interface.
	if [ "$IPADDR" ]; then
		# Prepare ifconfig options.
		OPTIONS=
		[ "$NETMASK" ] && OPTIONS="$OPTIONS netmask $NETMASK"
		[ "$BROADCAST" ] && OPTIONS="$OPTIONS broadcast $BROADCAST"
		[ "$POINTOPOINT" ] && OPTIONS="$OPTIONS pointopoint $POINTOPOINT"
	
		ifconfig $1 $IPADDR $OPTIONS
	fi

	# Update routing table.
	uname -r | grep "2.0.*" > /dev/null
	if [ $? -eq 0 ] 
	then
		[ "$POINTOPOINT" ] && route add -host $POINTOPOINT
	fi

	if [ "$GATEWAY" ]; then
		route add default gw $GATEWAY	
	fi

	return 0
}

# ----------------------------------------------------------------------------
# Start WAN wanrouter.
#	o create log file
#	o check configuration file presence
#	o load WAN drivers (using modprobe)
#	o configure drivers
#	o configure interfaces
# ----------------------------------------------------------------------------
router_load()
{
	echo "Starting WAN Router..."
	echo "`date`: starting WAN router" > $ROUTER_LOG

	if [ -e "/proc/net/wanrouter" ]; then
		return 0
	fi

	if [ ! -f "$MOD1" ]; then
		mod_error $MOD1
		return 1
	fi
        if [ ! -f "$MOD2" ]; then
		mod_error $MOD2 
                return 1
        fi           
        if [ ! -f "$MOD3" ]; then
		mod_error $MOD3 
                return 1
        fi       

	[ "$ROUTER_BOOT" = "NO" -o -z "$WAN_DRIVERS" ] && { 

		echo -e "\n\nERROR in $WANPIPE_CONF_DIR/wanrouter.rc file !!!" 
		echo -e "   ROUTER_BOOT is set to NO, OR" 
		echo -e "   WAN_DRIVERS must be set to wanpipe\n"
		echo -e "   wanrouter start failed !!!\n" 
		return 1
  	}

	echo -n "Loading WAN drivers: "
	for i in $WAN_DRIVERS
	do
		lsmod | grep -wq $i && continue
		echo -n "$i "
		echo -n "Loading driver $i ... " >> $ROUTER_LOG
		if modprobe $i 
		then 
			echo "ok" >> $ROUTER_LOG
		else 
			echo -e "\nFailed to load wanpipe modules !\n"
			echo "fail" >> $ROUTER_LOG
			router_unload	
			return 1
		fi
	done

	wansock_config LOAD

	echo "done."

	return 0
}

router_config()
{
	# Configure router.
	# $1 = /etc/wanpipe#.conf  where # is an integer
	wanconfig -v -f $1 >> $ROUTER_LOG 
}

interf_config()
{
	local device=$1
	local ROUTER_CONF=$2
	local int_file
	local INTERFACES
		
	#echo "============  iterf_config ================"

	# Configure network interfaces.
	[ -d "$IFCONF_DIR" ] || {
		error "Directory $IFCONF_DIR not found"
		return 1
	}

	#If TTY is defined there are no network interfaces
	eval "grep \"TTY.*=.*YES\" -i $ROUTER_CONF > /dev/null"
	if [ $? -eq 0 ]; then
		echo -e "done."
		return 0
	fi

	eval "grep \"WAN_EDU_KIT\" -i $ROUTER_CONF > /dev/null"
	if [ $? -eq 0 ]; then
		echo -e "done."
		return 0
	fi

	cd $IFCONF_DIR
	INTERFACES=`grep ".*=.*$device" -i $ROUTER_CONF | cut -d' ' -f1 2> /dev/null` 
	if [ -z "$INTERFACES" ]; then
		error "No interface definitions found in $ROUTER_CONF"
		return 1
	fi

	echo -n "Configuring interfaces: "
	for i in $INTERFACES
	do      
		int_file=${i%%=*}
		
		#Not every system has egrep. Egrep uses the regular expression matching. 
		
		which egrep > /dev/null
		if [ $? -eq 0 ]; then
			API=`egrep "$int_file[[:space:]]*=" -i $ROUTER_CONF | cut -d',' -f3 2> /dev/null`
		else
			API=`grep "$int_file =" -i $ROUTER_CONF | cut -d',' -f3 2> /dev/null`
		fi

		#If the card is in backup mode, it will be used to monitor
		#the primary link.  We don't want IP information, thus
		#we set the API field. This will cause the interface to 
		#come up without IP information.
		eval "grep \"BACKUP.*=.*YES\" -i $ROUTER_CONF > /dev/null"
		if [ $? -eq 0 ]; then
			API=API
		fi


		#Substitution and replacement are no supported
                #on bash versions lower than 2.0
			
		#if the card is configured as API, bring up all
		#interfaces without IP information.
		if [ ! -z $API ]; then

			#Remove all white spaces
			if [ $AWK_SUPPORT = YES ]; then
				API=`echo $API | awk '{ gsub(" ", "") ; print }'`
			elif [ $BASH_SUPPORT -gt 1 ]; then
				API=${API// /}
			fi
			
			if [ $API = API ]; then
				#cat /proc/net/dev | grep -wq $int_file || continue
				echo -n "$int_file "
				ifconfig $int_file up
				continue
			fi
			#brings up (for example wp1_fr16 and wp1_fr16e)
			#with IP addresses 0.0.0.0
			if [ $API = "BRIDGE" ];then

				# Bring up WANPIPE interface
				echo -n "$int_file "
				ifconfig $int_file up
				continue
			fi

		fi
		if [ $NEW_IF_TYPE = YES ]; then
			if_file=ifcfg-$int_file;
		else
			if_file=$int_file;
		fi

		if [ -s $if_file ]; then
			echo -n "$int_file "
			interface_up $int_file || {
				error "Failed to configure interface $int_file"
				continue
			}
		else
			echo "Error Interface File $int_file not found"
			return 1;
		fi
		
	done
	echo -e "\ndone."

	return 0
}

# ----------------------------------------------------------------------------
# Stop WAN router.
#	o shut down interfaces
#	o unload WAN drivers
#	o remove lock file
# ----------------------------------------------------------------------------
interf_down()
{
	local device=$1
	local ROUTER_CONF=$2
	local int_file
	local INTERFACES

	# Shut down network interfaces.
	[ -d "$IFCONF_DIR" ] && {
		cd $IFCONF_DIR
		INTERFACES=`grep ".*=.*$device" -i $ROUTER_CONF | cut -d' ' -f1 2> /dev/null`
		for i in $INTERFACES
		do
			int_file=${i%%=*}
			#cat /proc/net/dev | grep -wq $int_file || continue
			echo "Shutting down $device interface: $int_file"
			ifconfig $int_file down
		done
	}
}

router_unconfig()
{
	wanconfig -v -d $1 >> $ROUTER_LOG
	# Unload WAN drivers.
}

router_unload()
{
	wansock_config UNLOAD

	#IFS=:

	for i in $WAN_DRIVERS
	do lsmod | grep -wq $i && {
		modprobe -r $i
	}
	done
	rm -f $ROUTER_LOCK 2> /dev/null
}

mod_error()
{
	echo -e "\n"
        error "Wanpipe Module: $1 not found !!!"
        echo -e "        WANPIPE drivers must be compiled as modules"
        echo -e "        Check kernel configuration in /usr/src/linux/.config: "
        echo -e "             CONFIG_WAN_ROUTER=m"
        echo -e "             CONFIG_VENDOR_SANGOMA=m\n"               
}

get_distrib()
{
	grep -i "red *hat" "/etc/issue" > /dev/null 
	if [ $? -eq 0 ]
	then
		return 1; #RedHat Found
	else
		return 0;
	fi

}

check_config()
{
	for dev in $WAN_DEVICES; do
		check_file "$WANPIPE_CONF_DIR/$dev.conf" || {
				echo -e "\n$SCRIPT: Error, $WANPIPE_CONF_DIR/$dev.conf not found!\n";
				return 1;
				}
	done
	return 0;
}

check_file()
{
	local file=$1

	[ ! -f "$file" ] && {
			if [ ! -z $file ]; 
			then
				echo -e "ERROR: Wanpipe configuration file not found: $file\n"
			else
				echo -e "ERROR: Wanpipe configuration file not found in $WANPIPE_CONF_DIR\n"
			fi
			return 1;
	}
	return 0;
}

print_active_devices()
{
	local ac_list;
	local ac_wan;
	local rc=0;
	local silent=${1:-0}
	local devices

	echo -en "\t" 

	#If /proc directory doesn't exist nothing
        #to print, thus exit
	[ ! -d "$ROUTER_PROC" ] && return 0 

	cd $ROUTER_PROC

	devices=`cat $ROUTER_PROC/status | cut -d' ' -f1 | grep wanpipe | sort`
	if [ ! -z "$devices" ]; then
		if [  $silent -ne 0 ]; then	
			echo $devices
		fi
		rc=1;
	fi
	
#	ac_list=`ls wanpipe*`;
#	for ac_wan in $ac_list; do
#		res=`grep -i "Device is not configured" $ROUTER_PROC/$ac_wan 2> /dev/null`
#		[ -z "$res" ] && {
#			if [ $silent -ne 0 ]; then
#				echo -n "$ac_wan "
#			fi
#			rc=1;
#		}
#	done		
	echo -e "\n" 

	cd $ROUTER_HOME

	return $rc
}

check_running ()
{

	local device=$1
	local res

	
	[ ! -d "$ROUTER_PROC" ] && return 1  #Device not running

	cd $ROUTER_PROC
	

	if [ ! -f $ROUTER_PROC/$device ]; then 
		echo "Error: Device $device does not exist/not allocated."
		echo "       Check the messages log for the number of probed devices."
		echo
		return 0

	fi
	
	res=`cat $ROUTER_PROC/status | grep $device`
	[ ! -z "$res" ] && {
			#Device running
			return 0
		}
	
	#Device not running
	return 1;
}

check_and_print_still_running ()
{
	local devices 

	if [ ! -d $ROUTER_PROC ]; then
		return 1
	fi

	devices=`cat $ROUTER_PROC/status | cut -d' ' -f1 | grep wanpipe | sort`
	if [ ! -z "$devices" ]; then
		echo "Devices Still Running:"
		echo -ne "\t"
		echo $devices
		echo
		return 0
	fi

	return 1
}

create_ft1_conf () {

	local dev=$1
	local res

	wandev=`grep "wanpipe.*=" $WANPIPE_CONF_DIR/$dev.conf 2> /dev/null`
	res=$?
	if [ $res -eq 0 ]; then
		wandev=${wandev%%=*}
		if [ $AWK_SUPPORT = YES ]; then
			eval "wandev=`echo $wandev | awk '{ gsub(" ", "") ; print }'`"
		elif [ $BASH_SUPPORT -gt 1 ]; then
			wandev=${wandev// /}
		fi
	else
		echo -e "Error: Device name not found in $WANPIPE_CONF_DIR/$dev.conf\n"
		cleanup 1
	fi

	wancpu=`grep "S514CPU.*=.*" -i $WANPIPE_CONF_DIR/$dev.conf 2> /dev/null`
	wanslot_auto=`grep "AUTO_PCISLOT.*=.*" -i $WANPIPE_CONF_DIR/$dev.conf 2> /dev/null`
	wanslot=`grep "PCISLOT.*=.*" -i	$WANPIPE_CONF_DIR/$dev.conf 2> /dev/null`
	wanbus=`grep "PCIBUS.*=.*" -i	$WANPIPE_CONF_DIR/$dev.conf 2> /dev/null`
	wanio=`grep "IOPORT.*=.*" -i	$WANPIPE_CONF_DIR/$dev.conf 2> /dev/null`
	wanirq=`grep "IRQ.*=.*" -i	$WANPIPE_CONF_DIR/$dev.conf 2> /dev/null`

	if [ -z "$wancpu" -o -z "$wanslot" ]; then
		if [ -z "$wanio" -o -z "$wanirq" ]; then
			echo -e "Error: Missing fileds in $WANPIPE_CONF_DIR/$dev.conf" 
			echo -e "       configuraton file, in [$wandev] section.\n " 
			cleanup 1
		fi
	fi

	cat <<EOM > $WANPIPE_CONF_DIR/$FT1_CONF

#FT1 Configuration File
#
# Note: This file was automatically generated by wanrouter
#       script. 
#       DO NOT CHANGE IT
#
# CHDLC Protocol is used since, its firmware is the
# only one with FT1 configuration functions.

[devices]

$wandev = WAN_CHDLC, Cisco HDLC Firmware  

[$wandev]

$wancpu
$wanslot_auto
$wanslot
$wanbus

$wanio
$wanirq

Firmware        = $ROUTER_HOME/firmware/cdual514.sfm   # adapter firmware

#--------------------- END OF FT1 CONFIGURATION ------------------------

EOM

}


check_config_opt () 
{
	local dev=$1
	local opt=$2

	case $dev in

	ft1_wanpipe*) 

		#Strip off 'ft1_' from 'ft1_wanpipe#'
		dev=${dev##ft1_}

		#Check if wanpipe#.conf file exists
		check_file "$WANPIPE_CONF_DIR/$dev.conf"
		if [ $? -gt 0 ]; then
			cleanup 1
		fi

		#If we are starting the router up, create
		#the ft1.conf file in $WANPIPE_CONF_DIR directory
		if [ $opt -eq 0 ]; then
			create_ft1_conf $dev
		fi

		#Return string ft1
		result "ft1" 

		#Get the wanpipe device number, and return it
                #as a return code. This indicates that we want
                #to setup ft1 device
		dev=${dev##wanpipe}
		if [ $AWK_SUPPORT = YES ]; then
			dev=`echo $dev | awk '{ gsub(" ", "") ; print }'`
		elif [ $BASH_SUPPORT -gt 1 ]; then
			dev=${dev// /}
		fi
		return $dev
		;;
	
	wanpipe*) 
		#Check if wanpipe#.conf file exists
		check_file "$WANPIPE_CONF_DIR/$dev.conf"
		if [ $? -gt 0 ]; then
			cleanup 1
		fi

		#return string wanpipe#
		result $dev

		#return zero which indicates that we
		#want to startup reglar wanpipe device
		#not ft1 device
		return 0
		;;

	*)
		#Illegal syntax obtained
		echo "Error: Incorrect device name syntax !"
		cleanup 1
		;;
	esac

}

check_ft1_config ()
{
	local ft1=$1

	if [ $ft1 = ft1 ]; then
		return 0
	else
		return 1
	fi
}

result () {
	echo $1 > $RC
}

check_red_hat () {

	get_distrib 
	if [ $? -eq 1 ]; then 

		if [ $ROUTER_LOCK != "/var/lock/subsys/wanrouter" ]; then 
		echo -e "\nREDHAT Detected changing ROUTER_LOCK location"
	        echo -e "to /var/lock/subsys/wanrouter"
		echo -e "To avoid this message change the ROUTER_LOCK directory"
         	echo -e "in $WANPIPE_CONF_DIR/wanrouter.rc to /var/lock/subsys/wanrouter\n"
	 	ROUTER_LOCK=/var/lock/subsys/wanrouter
     		fi 
	fi

}

wansock_config ()
{
	local opt=$1

	if [ ! -f "$MOD4" ]; then
		return 0
	fi
	
	if [ $opt = UNLOAD ]; then
		lsmod | grep -wq "$AF_WANPIPE" && {
			modprobe -r $AF_WANPIPE
		}
	else 
		modprobe $AF_WANPIPE
	fi
	return 0
}

function enable_ip_forwarding () 
{
	ROUTER_IP_FORWARD=${ROUTER_IP_FORWARD:-NO}

	uname -r | grep "2.0.*" > /dev/null
	if [ $? -eq 0 ] 
	then
		#This option is not supported for 2.0.X kernels
		return;
	fi

	if [ $ROUTER_IP_FORWARD = YES ]; 
	then
		if [ -f "/proc/sys/net/ipv4/ip_forward" ]; then
			echo "Enabling IP Forwarding/Routing"
			echo "1" > /proc/sys/net/ipv4/ip_forward
		fi
	fi
}


function print_config_summary ()
{
	local pfiles;
	local pfile;
	local pdev;

	cd $ROUTER_HOME
	
	pfiles=`ls wanpipe*.conf 2> /dev/null`
	if [ $? -ne 0 ]; then
		echo "No Wanpipe configuration files found in $ROUTER_HOME";
		return;
	fi

	echo -e "Configuration File Summary in : $ROUTER_HOME\n"

	echo -e "Device\t\tProtocol\tType   Cpu/Io Slot/Irq  Bus\tState"
	echo -e "------------------------------------------------------------------------"

	for pfile in $pfiles
	do
		pdev=`grep "^wanpipe*=*" $pfile | cut -d'=' -f1 | cut -d' ' -f1 2> /dev/null`
		if [ $? -ne 0 ]; then
			continue
		fi
		echo -e -n "$pdev\t"
		
		pprot=`grep "^wanpiped*=*" $pfile | cut -d'=' -f2 | awk '{ gsub(" ", "") ; print }' | cut -d',' -f1`
		if [ $? -ne 0 ]; then
			continue
		fi

		if [ $pprot = WAN_BITSTRM ] || [ $pprot = WAN_CHDLC ] || [ $pprot = WAN_MULTPPP ]; then
			echo -e -n "$pprot\t"
		else
			echo -e -n "$pprot\t\t"
		fi

		phw=`grep "^S514CPU*" $pfile`
		if [ $? -eq 0 ]; then
			echo -e -n "PCI\t"
			
			pcpu=`grep -i "^S514CPU*" $pfile | cut -d'=' -f2 | awk '{ gsub(" ", "") ; print }' | cut -d',' -f1`
			echo -e -n "$pcpu\t"
			
			pslot=`grep -i "^PCISLOT*" $pfile | cut -d'=' -f2 | awk '{ gsub(" ", "") ; print }' | cut -d',' -f1`
			echo -e -n "$pslot\t"
			pbus=`grep -i "^PCIBUS*" $pfile | cut -d'=' -f2 | awk '{ gsub(" ", "") ; print }' | cut -d',' -f1`
			if [ -z $pbus ]; then
				echo -e -n "0\t"
			else
				echo -e -n "$pbus\t"
			fi	
			
		else
			echo -n -e "ISA\t"
			pport=`grep -i "^IOPORT*" $pfile | cut -d'=' -f2 | awk '{ gsub(" ", "") ; print }' | cut -d',' -f1`
			echo -e -n "$pport\t"
			pport=`grep -i "^IRQ*" $pfile | cut -d'=' -f2 | awk '{ gsub(" ", "") ; print }' | cut -d',' -f1`
			echo -e -n "$pport\t"
			
			echo -e -n "n/a\t"
		fi

		if [ -e /proc/net/wanrouter ]; then
			pstate=`cat /proc/net/wanrouter/status | grep $pdev | cut -d'|' -f4 | awk '{ gsub(" ", "") ; print }'`
			if [ -z $pstate ]; then
				echo -e -n "Inactive\t"
			else
				echo -e -n "$pstate\t"
			fi
		else

			echo -e -n "Inactive\t"
		fi
		
		echo 
		
	done
}

####### MAIN #################################################################
# set -x

export PATH=/sbin:/bin:/usr/sbin:/usr/bin
ROUTER_VERSION=beta3-2.2.4
ROUTER_HOME=/etc/wanpipe
ROUTER_RC=$ROUTER_HOME/wanrouter.rc
IFCONF_DIR=$ROUTER_HOME/interfaces
SCRIPT=wanrouter
REDHAT=/usr/src/redhat
ROUTER_PROC=/proc/net/wanrouter
WAN_DRIVERS=wanpipe
AF_WANPIPE=af_wanpipe
WAN_LOCK=/var/lock/wanpipe_lock

check_bash
check_awk

uname -r | grep "2.4.*" > /dev/null
if [ $? -eq 0 ]; then
	MOD1=/lib/modules/$(uname -r)/kernel/net/wanrouter/wanrouter.o
	MOD2=/lib/modules/$(uname -r)/kernel/drivers/net/wan/wanpipe.o
	MOD3=/lib/modules/$(uname -r)/kernel/drivers/net/wan/sdladrv.o
	MOD4=/lib/modules/$(uname -r)/kernel/net/wanrouter/af_wanpipe.o
else
	MOD1=/lib/modules/$(uname -r)/misc/wanrouter.o
	MOD2=/lib/modules/$(uname -r)/net/wanpipe.o
	MOD3=/lib/modules/$(uname -r)/net/sdladrv.o
	MOD4=/lib/modules/$(uname -r)/misc/af_wanpipe.o
fi


# Return code 
RC=$(pwd)/return_code
GET_RC="cat $RC"
FT1_CONF=ft1.conf

# Ignore interrupt signals.
trap '' 2

# Read meta-configuration file.
if [ -f $ROUTER_RC ]
then . $ROUTER_RC
else 
	echo "$SCRIPT: WARNING: $ROUTER_RC not found!"
	exit 1;
fi

NEW_IF_TYPE=${NEW_IF_TYPE:-NO}
IFCONF_DIR=$WANPIPE_INTR_DIR
LINUX_DISTR=unknown


if [ -f $WAN_LOCK ]; then
	echo -e "\nERROR: wanrouter script already running!\n";
	cleanup 0;
fi

touch $WAN_LOCK

check_red_hat

eval "grep \"Debian\" -i /etc/issue > /dev/null"
if [ $? -eq 0 ]; then 
	LINUX_DISTR=debian	
fi
eval "grep \"Red *Hat\" -i /etc/issue > /dev/null"
if [ $? -eq 0 ]; then
	LINUX_DISTR=redhat	
fi
eval "grep \"Mandrake\" -i /etc/issue > /dev/null"
if [ $? -eq 0 ]; then
	LINUX_DISTR=redhat	
fi


echo
# See how we were called.
case "$1" in
	start)	

		enable_ip_forwarding;

		# ROUTER START
		if [ -z $2 ]; then	

			check_config || cleanup 1

			[ -f "$ROUTER_LOCK" ] && {
				echo -e "Router is already running. Stop it first!\n"
				cleanup 1
			}
			router_load
			if [ $? -eq 0 ]; then
				touch $ROUTER_LOCK
			else
				cleanup 2
			fi

			for dev in $WAN_DEVICES; do
				[ ! -e "$ROUTER_PROC/$dev" ] && {
					echo -e "Error: Device $dev is not supported by kernel\n"
					continue	
				}
				ROUTER_CONF=$WANPIPE_CONF_DIR/$dev.conf
				echo "Starting up device: $dev"
				echo "Starting up device: $dev" >> $ROUTER_LOG
				router_config $ROUTER_CONF
				if [ $? -ne 0 ]; then
					#echo "Exiting rc = 3"
					cleanup 3
				fi
			done
			
			for dev in $WAN_DEVICES; do
				ROUTER_CONF=$WANPIPE_CONF_DIR/$dev.conf
				interf_config $dev $ROUTER_CONF
				if [ $? -ne 0 ]; then
					cleanup 4
				fi
			done

		else
		#ROUTER START WANPIPE
			
			[ -f $WANPIPE_CONF_DIR/$FT1_CONF ] && rm -f $WANPIPE_CONF_DIR/$FT1_CONF
			dev=$2

			#Parse the dev name, and if it starts with
			#ft1 than it means we should load the ft1 
 			#driver.  
			check_config_opt $dev 0
			ft1_or_wanpipe=$?
			dev=$($GET_RC)
			rm -f $RC

			ROUTER_CONF=$WANPIPE_CONF_DIR/$dev.conf

			check_file $ROUTER_CONF || cleanup 1
	
			[ ! -f "$ROUTER_LOCK" ] && {
				router_load
				if [ $? -eq 0 ]; then
					touch $ROUTER_LOCK
				else
					cleanup 2
				fi
			}	

			#If we are starting FT1 driver, we have to check
			#wether the actual wanpipe# device is running or
                        #not, thus name dev has to be changed to 'wanpipe#'
			if [ $ft1_or_wanpipe -gt 0 ]; then
				dev="wanpipe$ft1_or_wanpipe"
			fi 


			if [ ! -f $ROUTER_PROC/$dev ]; then 
				echo "Error: Device $dev does not exist/not allocated."
				echo "       Check the messages log for the number of probed devices."
				echo
				cleanup 1
			fi

			res=`cat $ROUTER_PROC/status | grep $dev`
			if [ ! -z "$res" ]; then
				echo "Error: Device $dev is still running"
				echo -e "    Run 'wanrouter stop $dev' first\n"
				cleanup 1
			fi
	
			#Since we changed the name of dev above,
			#we must check if we are running ft1 device,
                        #output a correct message	
			if [ $ft1_or_wanpipe -gt 0 ]; then
				echo "Starting up device: $dev, FT1 config mode"
				echo "Starting up device: $dev, FT1 config mode" >> $ROUTER_LOG
			else
				echo "Starting up device: $dev"
				echo "Starting up device: $dev" >> $ROUTER_LOG
			fi
			router_config $ROUTER_CONF
			if [ $? -ne 0 ]; then
				cleanup 3
			fi
				

			#When loading ft1 device there are not interfaces
			if [ $ft1_or_wanpipe -eq 0 ]; then
				interf_config $dev $ROUTER_CONF
				if [ $? -ne 0 ]; then
					cleanup 4
				fi
			fi
		fi
		;;
	stop)	
		
		#WANROUTER STOP
		if [ -z $2 ]; then

			#Check that all wanpipe#.conf file defined in 
			# WAN_DEVICES exist
			check_config || cleanup 1

			[ ! -f "$ROUTER_LOCK" -o ! -d "$ROUTER_PROC" ] && {
				router_unload
				echo -e "Router is already stopped !\n"
				cleanup 1
			}

			#Stop all interfaces, but check whether 
                        #device is running first
			for dev in $WAN_DEVICES; do
				ROUTER_CONF=$WANPIPE_CONF_DIR/$dev.conf
				interf_down $dev $ROUTER_CONF
			done

			#Stop all routers but check if device
			#is running first
			for dev in $WAN_DEVICES; do
				ROUTER_CONF=$WANPIPE_CONF_DIR/$dev.conf
				echo "Shutting down device: $dev"
				echo "Shutting down device: $dev" >> $ROUTER_LOG
				router_unconfig $ROUTER_CONF
			done


			#Check if any devices are still running
			#  If YES: don't unload the modules, just printout
			#	   the list of active devices
			#  If NO:  unload modules
			check_and_print_still_running && cleanup 0

			echo -e "No devices running, Unloading Modules"
			router_unload

		else
		#WANROUTER STOP WANPIPE

			dev=$2

			check_config_opt $dev 1
			ft1_or_wanpipe=$?
			dev=$($GET_RC)
			rm -f $RC

			ROUTER_CONF=$WANPIPE_CONF_DIR/$dev.conf

			#Check that all configuration files exist
			check_file $ROUTER_CONF || cleanup 1

			#Check that modules are up and running
			[ ! -f "$ROUTER_LOCK" -o ! -d "$ROUTER_PROC" ] && {
				router_unload
				echo -e "Router is already stopped !\n";
				cleanup 1;
			}

			#If we are stopping FT1 driver, we have to check
			#whether the actual wanpipe# device is running or
                        #not, thus name dev has to be changed to 'wanpipe#'
			if [ $ft1_or_wanpipe -gt 0 ]; then
				dev="wanpipe$ft1_or_wanpipe"
			fi 

			#If we are starting ft1 device there are no
                        #interfaces. 
			if [  $ft1_or_wanpipe -gt 0 ]; then
				echo "Shutting down device: $dev, FT1 config mode"
				echo "Shutting down device: $dev, FT1 config mode" >> $ROUTER_LOG
			else
				interf_down $dev $ROUTER_CONF
				echo "Shutting down device: $dev"
				echo "Shutting down device: $dev" >> $ROUTER_LOG
			fi
			router_unconfig $ROUTER_CONF
			
			[ -f $WANPIPE_CONF_DIR/$FT1_CONF ] && rm -f $WANPIPE_CONF_DIR/$FT1_CONF

			#Check if any devices are still running
			#  If YES: don't unload the modules, just printout
			#	   the list of active devices
			#  If NO:  unload modules
	
			check_and_print_still_running && cleanup 0

			cd $ROUTER_HOME
			echo -e "No devices running, Unloading Modules"
			router_unload

		fi			
		;;
	list)
		
		[ -f "$ROUTER_LOCK" ] || {
				echo -e "Router is stopped !\n";
				cleanup 0;
		}
		
		echo -e "Devices currently active:"
		print_active_devices 1;
		cleanup 0;
		;;

	restart)
		eval "rm -f $WAN_LOCK 2> /dev/null > /dev/null"
		if [ "$2" = "" ]; then
			$0 stop;
			$0 start;
		else
			$0 stop $2;
			$0 start $2;
		fi
		cleanup 0;

		;;
	modules)

		cat /proc/modules | grep wan;
		cleanup 0;

		;;
	status)

		[ -f "$ROUTER_LOCK" ] || {
				echo -e "Router is stopped !\n";
				exit 0;
		}

		echo -e "Devices currently active:"
		print_active_devices 1;

		echo -e "Wanpipe Config:\n"
		cat /proc/net/wanrouter/config | sort

		echo -e "\nWanrouter Status:\n"
		cat /proc/net/wanrouter/status | sort
		echo ""

		cleanup 0;
		;;


	summary)
		print_config_summary;
		cleanup 0;
		;;

	hwprobe)
		modprobe wanpipe
		cat /proc/net/wanrouter/hwprobe
		cleanup 0;
		;;
		
	version)
		echo "WANPIPE Release: $ROUTER_VERSION"
		;;
		
	*)	echo -e "\nWANPIPE: WAN Router startup script\n"
		echo -e "Usage: $SCRIPT: {options} <wanpipe#>\n"
		echo -e "       wanrouter start : Starts all devices specified in"
		echo -e "                      $WANPIPE_CONF_DIR/wanrouter.rc WAN_DEVICES\n"
		echo -e "       wanrouter stop  : Stops all devices specified in"
		echo -e "                      $WANPIPE_CONF_DIR/wanrouter.rc WAN_DEVICES\n"
		echo -e "       wanrouter start wanpipe# : Start a single device\n"
		echo -e "       wanrouter stop wanpipe#  : Stops a single device" 
		echo -e "                               (# can range from 1 to 16)\n"
		echo -e "	wanrouter restart	 : Restart all devices specified in"
		echo -e "                      $WANPIPE_CONF_DIR/wanrouter.rc WAN_DEVICES\n"
		echo -e "	wanrouter restart wanpipe# : Restart a single device"
		echo -e "                               (# can range from 1 to 16)\n"
		echo -e " 	wanrouter list		: List all active devices\n"
		echo -e "	wanrouter modules	: Show wanpipe kernel modules\n"
		echo -e "	wanrouter status	: Display status for all active devices\n"
		echo -e "	wanrouter summary	: Summary of config files in $ROUTER_HOME\n"
		echo -e "	wanrouter hwprobe	: Display wanpipe hardware probe info.\n"
		echo -e "	wanrouter version	: wanpipe version information.\n"
		cleanup 0
		;;
esac
echo
cleanup 0
exit 0
