#!/bin/bash -p
#
# Setup		WANPIPE WAN Router Installation/Removal Script.
#
# Copyright	(c) 1996-2013, 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.
# ----------------------------------------------------------------------------
# Sep 04, 2010  Evandro Arruda  Rewrite --builddir support on Makefile's
# May 10, 2010  Yannick Lam     Added support for OSLEC for DAHDI only (--with-oslec)
# Apr 22, 2010  Yannick Lam     Added support for dahdi-2.3 for various chunksize
# Oct 29, 2009	Yannick Lam		Added --no_woomera option (will not install woomera)
# Jul 29, 2009  Konrad Hammel   Added --with-asterisk option
# Jul 27, 2009  Konrad Hammel   Update to not compile unneeded utilities in 
#				                TDM_VOICE mode.
# Jul 24, 2008  Konrad Hammel 	Removed the addition of UDEV rules for Dahdi
#                             	installs, only needed for Zaptel
# Jul 30, 2008  Jignesh Patel 	Added check for sctp utlity
# May 30, 2008  Jignesh Patel   Fixed bootscript installation failure
# Mar 12, 2008  Konrad Hammel   Updated for Zaptel-1.4.9 (kernel sub-dir)
# Jan 24, 2008  Jignesh Patel   Zaptel Patch Update for 1.4.x 
# Nov 13, 2007  Konrad Hammel   Minor Updates for aesthetics and usability
# Nov 27, 2005  David Rokhvarg 	Added Echo Debugging option
# Mar 18, 2002  Nenad Corbic	Added BSCSTRM protocol
# Mar 01, 2002  Nenad Corbic	Added option to split rpm build into
#				                two packages: util and mod.
# Jan 05, 2002  Nenad Corbic	Updated for 2.2.4 Release
# Mar 02, 2001  Nenad Corbic	Added 2.4.2 kernel support
#				                Added a check for MODVERSIONS
# Feb 21, 2001  Nenad Corbic	Fixed the kernel gcc compile bug.
# Feb 20, 2001  Nenad Corbic	Fixed the kernel upgrade bug.
# Jan 31, 2001  Nenad Corbic	Updated all help messages
#				                Added kernel upgrade feature
#				                Added WANPIPE driver compile feature
# Dec 25, 2000  Nenad Corbic	Updated for v2.2.0
# Feb 29, 2000  Nenad Corbic    Removed print statements in file verification
#                               procedure.
# Oct 04, 1999  Nenad Corbic    Updated for v2.1.0
# Aug 26, 1999  Nenad Corbic    Updated for v2.0.7
# Aug 04, 1999  Nenad Corbic    Updated for v2.0.5
# Oct 13, 1998	Jaspreet Singh	Updated for v2.0.4
# Aug 31, 1998	Jaspreet Singh	Updated for v2.0.3
# Dev 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
# Oct 16, 1997	Jaspreet Singh	Added UID = 0 check
# Aug 26, 1997  Farhan Thawar   Added patches.txt info 
# Jul 28, 1997	Jaspreet Singh	Updated for v1.0.5
# Jul 10, 1997  Jaspreet Singh	Updated for v1.0.4
# Jan 15, 1997	Gene Kozin	    Added patch selection and upgrade features
# Dec 16, 1996	Gene Kozin	    Initial version based on Sangoma's WANPIPE(tm)
# ============================================================================

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

# ----------------------------------------------------------------------------
# Clear the screen if it is supported.
# ----------------------------------------------------------------------------
clearscr()
{
	if [ $setup_install_quick = "YES" ]; then
		[ "$TERM" ] && clear 2> /dev/null
		return
	fi

	if test $NONINTERACTIVE; then
		return
	fi

	# check if the terminal environment is set up
	[ "$TERM" ] && clear 2> /dev/null
}

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

check_gcc ()
{
    if [ "$USR_CC" != "" ]; then
        eval "$USR_CC --version 2> /dev/null > /dev/null"
        if [ $? -ne 0 ]; then 
         	echo "Error: Failed to find version of $USR_CC"
        	return 1;
        fi
        eval "$USR_CC --version | grep \"^2\" > /dev/null"
        if [ $? -eq 0 ]; then
           GCC_VER=2;
        else
           GCC_VER=3;
        fi    
        return 0;                       
    fi

	if [ "$GCC_CHECK" = "INIT" ]; then
	    GCC_CHECK=DONE
	else
	    return 0
	fi

	GCC_VER=3

	eval "gcc --version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		CC=gcc

		cd $DRIVER_UPDATE_DIR/src/net
		eval "gcc --version | grep \"^2\" > /dev/null"
		if [ $? -eq 0 ]; then
			GCC_VER=2;
		else
			GCC_VER=3;
		fi

		cd $PROD_HOME
		return 0;
	fi
	
	eval "cc --version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		CC=cc
		return 0;
	fi	

	return 1
}

check_awk ()
{
	eval "type awk 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		AWK_SUPPORT=YES
	else
		AWK_SUPPORT=NO
	fi
}
#fix for 2.6.18 kernels
check_inode_struct ()
{
	if [ -e $SOURCEDIR/include/linux/fs.h ];then
		eval "grep i_private $SOURCEDIR/include/linux/fs.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DWANPIPE_USE_I_PRIVATE" 
		fi 
	fi	
}

check_kern_pde_feature ()
{
	if [ -e $SOURCEDIR/include/linux/proc_fs.h ];then
		eval "grep PDE_DATA $SOURCEDIR/include/linux/proc_fs.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			PDE_FEATURE="-DKERN_PROC_PDE_FEATURE=1"
		else
			PDE_FEATURE="-DKERN_PROC_PDE_FEATURE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $PDE_FEATURE "
	elif [ -e $DEBSRCDIR/include/linux/proc_fs.h ];then
		eval "grep PDE_DATA $DEBSRCDIR/include/linux/proc_fs.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			PDE_FEATURE="-DKERN_PROC_PDE_FEATURE=1"
		else
			PDE_FEATURE="-DKERN_PROC_PDE_FEATURE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $PDE_FEATURE " 
		
	fi	

	if [ -e $SOURCEDIR/include/linux/proc_fs.h ];then
		eval "grep -A 2 \"proc_create\" $SOURCEDIR/include/linux/proc_fs.h | grep file_operations > /dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			PROC_FEATURE="-DKERN_PROC_CREATE=1"
		else
			PROC_FEATURE="-DKERN_PROC_CREATE=0"
		fi
	elif [ -e $DEBSRCDIR/include/linux/proc_fs.h ];then
		eval "grep -A 2 \"proc_create\" $DEBSRCDIR/include/linux/proc_fs.h | grep file_operations > /dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			PROC_FEATURE="-DKERN_PROC_CREATE=1"
		else
			PROC_FEATURE="-DKERN_PROC_CREATE=0"
		fi
	else
		PROC_FEATURE="-DKERN_PROC_CREATE=0"
	fi
	PROTOCOL_DEFINES="$PROTOCOL_DEFINES $PROC_FEATURE "
}

check_kern_sock_for_feature ()
{
	if [ -e $SOURCEDIR/include/net/sock.h ];then
		eval "grep \"sk_for_each.*node\" $SOURCEDIR/include/net/sock.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			KERN_SK_FOR_NODE_FEATURE="-DKERN_SK_FOR_NODE_FEATURE=1"
		else
			KERN_SK_FOR_NODE_FEATURE="-DKERN_SK_FOR_NODE_FEATURE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_SK_FOR_NODE_FEATURE " 

	elif [ -e $DEBSRCDIR/include/net/sock.h ];then 
		eval "grep \"sk_for_each.*node\" $DEBSRCDIR/include/net/sock.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			KERN_SK_FOR_NODE_FEATURE="-DKERN_SK_FOR_NODE_FEATURE=1"
		else
			KERN_SK_FOR_NODE_FEATURE="-DKERN_SK_FOR_NODE_FEATURE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_SK_FOR_NODE_FEATURE " 
	fi	

        if [ -e $SOURCEDIR/include/net/sock.h ];then
                eval "grep \"sock_no_setsockopt\" $SOURCEDIR/include/net/sock.h >/dev/null 2>/dev/null"
                if [ $? -eq 0 ]; then
                        SOCK_NO_OPT="-DSOCK_NO_OPT=1"
                else
                        SOCK_NO_OPT="-DSOCK_NO_OPT=0"
                fi
                PROTOCOL_DEFINES="$PROTOCOL_DEFINES $SOCK_NO_OPT "

        elif [ -e $DEBSRCDIR/include/net/sock.h ];then
                eval "grep \"sock_no_setsockopt\" $DEBSRCDIR/include/net/sock.h >/dev/null 2>/dev/null"
                if [ $? -eq 0 ]; then
                        SOCK_NO_OPT="-DSOCK_NO_OPT=1"
                else
                        SOCK_NO_OPT="-DSOCK_NO_OPT=0"
                fi
                PROTOCOL_DEFINES="$PROTOCOL_DEFINES $SOCK_NO_OPT "
        fi
}

check_kern_netdevice_feature ()
{
	if [ -e $SOURCEDIR/include/linux/netdevice.h ];then
		eval "grep \"netif_trans_update\" $SOURCEDIR/include/linux/netdevice.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_NETIF_TRANS_UPDATE="-DKERN_NETIF_TRANS_UPDATE=1"
		else
			KERN_NETIF_TRANS_UPDATE="-DKERN_NETIF_TRANS_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_NETIF_TRANS_UPDATE "

	elif [ -e $DEBSRCDIR/include/linux/netdevice.h ];then
		eval "grep \"netif_trans_update\" $DEBSRCDIR/include/linux/netdevice.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_NETIF_TRANS_UPDATE="-DKERN_NETIF_TRANS_UPDATE=1"
		else
			KERN_NETIF_TRANS_UPDATE="-DKERN_NETIF_TRANS_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_NETIF_TRANS_UPDATE "
	fi


	if [ -e $SOURCEDIR/include/linux/netdevice.h ];then
		eval "grep \"ndo_change_mtu_rh74\" $SOURCEDIR/include/linux/netdevice.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_NDO_CHANGE_MTU_RH74="-DKERN_NDO_CHANGE_MTU_RH74=1"
		else
			KERN_NDO_CHANGE_MTU_RH74="-DKERN_NDO_CHANGE_MTU_RH74=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_NDO_CHANGE_MTU_RH74 "

	elif [ -e $DEBSRCDIR/include/linux/netdevice.h ];then
		eval "grep \"ndo_change_mtu_rh74\" $DEBSRCDIR/include/linux/netdevice.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_NDO_CHANGE_MTU_RH74="-DKERN_NDO_CHANGE_MTU_RH74=1"
		else
			KERN_NDO_CHANGE_MTU_RH74="-DKERN_NDO_CHANGE_MTU_RH74=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_NDO_CHANGE_MTU_RH74 "
	fi

	if [ -e $SOURCEDIR/include/linux/netdevice.h ];then
		eval "grep -A 1 \"dev_change_flags\" $SOURCEDIR/include/linux/netdevice.h | grep netlink_ext_ack >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			NET_DEVICE_DEV_CHG_FLAG_UPDATE="-DKERN_DEV_CHG_FLAG_UPDATE=1"
		else
			NET_DEVICE_DEV_CHG_FLAG_UPDATE="-DKERN_DEV_CHG_FLAG_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $NET_DEVICE_DEV_CHG_FLAG_UPDATE "
	elif [ -e $DEBSRCDIR/include/linux/netdevice.h ];then
		eval "grep -A 1 \"dev_change_flags\" $DEBSRCDIR/include/linux/netdevice.h | grep netlink_ext_ack >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			NET_DEVICE_DEV_CHG_FLAG_UPDATE="-DKERN_DEV_CHG_FLAG_UPDATE=1"
		else
			NET_DEVICE_DEV_CHG_FLAG_UPDATE="-DKERN_DEV_CHG_FLAG_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $NET_DEVICE_DEV_CHG_FLAG_UPDATE "
	else
		NET_DEVICE_DEV_CHG_FLAG_UPDATE="-DKERN_DEV_CHG_FLAG_UPDATE=0"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $NET_DEVICE_DEV_CHG_FLAG_UPDATE "
	fi


	if [ -e $SOURCEDIR/include/linux/netdevice.h ];then
		eval "grep -A 2 \"ndo_tx_timeout\" $SOURCEDIR/include/linux/netdevice.h | grep txqueue >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			NET_DEVICE_NDO_UPDATE="-DKERN_NDO_TIMEOUT_UPDATE=1"
		else
			NET_DEVICE_NDO_UPDATE="-DKERN_NDO_TIMEOUT_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $NET_DEVICE_NDO_UPDATE "
	elif [ -e $DEBSRCDIR/include/linux/netdevice.h ];then
		eval "grep -A 2 \"ndo_tx_timeout\" $DEBSRCDIR/include/linux/netdevice.h | grep txqueue >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			NET_DEVICE_NDO_UPDATE="-DKERN_NDO_TIMEOUT_UPDATE=1"
		else
			NET_DEVICE_NDO_UPDATE="-DKERN_NDO_TIMEOUT_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $NET_DEVICE_NDO_UPDATE "
	else
		NET_DEVICE_NDO_UPDATE="-DKERN_NDO_TIMEOUT_UPDATE=0"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $NET_DEVICE_NDO_UPDATE "
	fi
}

check_kern_memcpy_from_msg ()
{
	if [ -e $SOURCEDIR/include/linux/skbuff.h ];then
		eval "grep \"memcpy_from_msg\" $SOURCEDIR/include/linux/skbuff.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			MEMCPY_FROM_MSG_FEATURE="-DKERN_MEMCPY_FROM_MSG=1"
		else
			MEMCPY_FROM_MSG_FEATURE="-DKERN_MEMCPY_FROM_MSG=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $MEMCPY_FROM_MSG_FEATURE "
	elif [ -e $DEBSRCDIR/include/linux/skbuff.h ];then
		eval "grep \"memcpy_from_msg\" $DEBSRCDIR/include/linux/skbuff.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			MEMCPY_FROM_MSG_FEATURE="-DKERN_MEMCPY_FROM_MSG=1"
		else
			MEMCPY_FROM_MSG_FEATURE="-DKERN_MEMCPY_FROM_MSG=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $MEMCPY_FROM_MSG_FEATURE "
	fi
}

check_kern_memcpy_to_msg ()
{
	if [ -e $SOURCEDIR/include/linux/skbuff.h ];then
		eval "grep \"memcpy_to_msg\" $SOURCEDIR/include/linux/skbuff.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			MEMCPY_TO_MSG_FEATURE="-DKERN_MEMCPY_TO_MSG=1"
		else
			MEMCPY_TO_MSG_FEATURE="-DKERN_MEMCPY_TO_MSG=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $MEMCPY_TO_MSG_FEATURE "
	elif [ -e $DEBSRCDIR/include/linux/skbuff.h ];then
		eval "grep \"memcpy_to_msg\" $DEBSRCDIR/include/linux/skbuff.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			MEMCPY_TO_MSG_FEATURE="-DKERN_MEMCPY_TO_MSG=1"
		else
			MEMCPY_TO_MSG_FEATURE="-DKERN_MEMCPY_TO_MSG=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $MEMCPY_TO_MSG_FEATURE "
	fi
}

check_kern_dev_group_struct ()
{
	if [ -e $SOURCEDIR/include/linux/device.h ];then
		eval "grep \"\*\*dev_groups;\" $SOURCEDIR/include/linux/device.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			DEV_GRP_STRUCT="-DKERN_CLASS_DEV_GROUPS=1"
		fi
	elif [ -e $DEBSRCDIR/include/linux/device.h ];then
		eval "grep \"\*\*dev_groups;\" $DEBSRCDIR/include/linux/device.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			DEV_GRP_STRUCT="-DKERN_CLASS_DEV_GROUPS=1"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $DEV_GRP_STRUCT "
	fi

	if [[ "$DEV_GRP_STRUCT" != "-DKERN_CLASS_DEV_GROUPS=1" ]];then
		if [ -e $SOURCEDIR/include/linux/device/bus.h ];then
			eval "grep \"\*\*dev_groups;\" $SOURCEDIR/include/linux/device/bus.h >/dev/null 2>/dev/null"
			if [ $? -eq 0 ]; then
				DEV_GRP_STRUCT="-DKERN_CLASS_DEV_GROUPS=1"
			else
				DEV_GRP_STRUCT="-DKERN_CLASS_DEV_GROUPS=0"
			fi
		elif [ -e $DEBSRCDIR/include/linux/device/bus.h ];then
			eval "grep \"\*\*dev_groups;\" $DEBSRCDIR/include/linux/device/bus.h >/dev/null 2>/dev/null"
			if [ $? -eq 0 ]; then
				DEV_GRP_STRUCT="-DKERN_CLASS_DEV_GROUPS=1"
			else
				DEV_GRP_STRUCT="-DKERN_CLASS_DEV_GROUPS=0"
			fi
		else
			DEV_GRP_STRUCT="-DKERN_CLASS_DEV_GROUPS=0"
		fi

	fi
	PROTOCOL_DEFINES="$PROTOCOL_DEFINES $DEV_GRP_STRUCT "
}

check_kern_timer_struct ()
{
	if [ -e $SOURCEDIR/include/linux/timer.h ];then
		eval "grep \"define timer_setup\" $SOURCEDIR/include/linux/timer.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			TIMER_STRUCT="-DKERN_TIMER_SETUP=1"
		else
			TIMER_STRUCT="-DKERN_TIMER_SETUP=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $TIMER_STRUCT "
	elif [ -e $DEBSRCDIR/include/linux/timer.h ];then
		eval "grep \"define timer_setup\" $DEBSRCDIR/include/linux/timer.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			TIMER_STRUCT="-DKERN_TIMER_SETUP=1"
		else
			TIMER_STRUCT="-DKERN_TIMER_SETUP=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $TIMER_STRUCT "
	fi

	if [ -e $SOURCEDIR/include/linux/types.h ];then
		eval "grep \"define timer_setup\" $SOURCEDIR/include/linux/t* >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			TIMER_32BIT="-DKERN_TIMER_32BIT=1"
		else
			TIMER_32BIT="-DKERN_TIMER_32BIT=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $TIMER_32BIT "
	elif [ -e $DEBSRCDIR/include/linux/types.h ];then
		eval "grep \"define timer_setup\" $DEBSRCDIR/include/linux/t* >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			TIMER_32BIT="-DKERN_TIMER_32BIT=1"
		else
			TIMER_32BIT="-DKERN_TIMER_32BIT=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $TIMER_32BIT "
	fi
}

check_kern_refcount_feature ()
{
	if [ -e $SOURCEDIR/include/linux/refcount.h ];then
		eval "grep \"refcount_read\" $SOURCEDIR/include/linux/refcount.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			REFCOUNT_UPDATE="-DKERN_REFCNT_UPDATE=1"
		else
			REFCOUNT_UPDATE="-DKERN_REFCNT_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $REFCOUNT_UPDATE "
	elif [ -e $DEBSRCDIR/include/linux/refcount.h ];then
		eval "grep \"refcount_read\" $DEBSRCDIR/include/linux/refcount.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			REFCOUNT_UPDATE="-DKERN_REFCNT_UPDATE=1"
		else
			REFCOUNT_UPDATE="-DKERN_REFCNT_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $REFCOUNT_UPDATE "
	fi
}

check_kern_signal_feature ()
{
	if [ -e $SOURCEDIR/include/linux/sched/signal.h ];then
		eval "grep \"signal_pending\" $SOURCEDIR/include/linux/sched/signal.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			SIGNAL_UPDATE="-DKERN_SIG_UPDATE=1"
		else
			SIGNAL_UPDATE="-DKERN_SIG_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $SIGNAL_UPDATE "
	elif [ -e $DEBSRCDIR/include/linux/sched/signal.h ];then
		eval "grep \"signal_pending\" $DEBSRCDIR/include/linux/sched/signal.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			SIGNAL_UPDATE="-DKERN_SIG_UPDATE=1"
		else
			SIGNAL_UPDATE="-DKERN_SIG_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $SIGNAL_UPDATE "
	fi
}

check_kern_proto_ops_struct ()
{
	if [ -e $SOURCEDIR/include/linux/net.h ];then
		eval "grep -A2 \"*getname\" $SOURCEDIR/include/linux/net.h | grep \"sockaddr_len\" >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			PROTO_OPS_UPDATE="-DKERN_CLASS_PROTO_OPS_UPDATE=1"
		else
			PROTO_OPS_UPDATE="-DKERN_CLASS_PROTO_OPS_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $PROTO_OPS_UPDATE "
	elif [ -e $DEBSRCDIR/include/linux/net.h ];then
		eval "grep -A2 \"*getname\" $DEBSRCDIR/include/linux/net.h | grep \"sockaddr_len\" >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			PROTO_OPS_UPDATE="-DKERN_CLASS_PROTO_OPS_UPDATE=1"
		else
			PROTO_OPS_UPDATE="-DKERN_CLASS_PROTO_OPS_UPDATE=0"
		fi
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES $PROTO_OPS_UPDATE "
	fi
}

check_kern_timeofday ()
{
	if [ -e $SOURCEDIR/include/linux/time.h ];then
		eval "grep \"do_gettimeofday\" $SOURCEDIR/include/linux/time* >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_TIME_UPDATE="-DKERN_DO_GET_TIME=1"
		else
			KERN_TIME_UPDATE="-DKERN_DO_GET_TIME=0"
		fi
	elif [ -e $DEBSRCDIR/include/linux/time.h ];then
		eval "grep \"do_gettimeofday\" $DEBSRCDIR/include/linux/time* >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_TIME_UPDATE="-DKERN_DO_GET_TIME=1"
		else
			KERN_TIME_UPDATE="-DKERN_DO_GET_TIME=0"
		fi
	else
		KERN_TIME_UPDATE="-DKERN_DO_GET_TIME=0"
	fi
	PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_TIME_UPDATE "
}

check_kern_ds ()
{
	if [ -e $SOURCEDIR/include/asm-generic/uaccess.h ];then
		eval "grep \"define get_ds\" $SOURCEDIR/include/asm-generic/uaccess.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_DS_UPDATE="-DKERN_GET_KENEL_DS=1"
		else
			KERN_DS_UPDATE="-DKERN_GET_KENEL_DS=0"
		fi
	elif [ -e $DEBSRCDIR/include/asm-generic/uaccess.h ];then
		eval "grep \"define get_ds\" $DEBSRCDIR/include/asm-generic/uaccess.h >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_DS_UPDATE="-DKERN_GET_KENEL_DS=1"
		else
			KERN_DS_UPDATE="-DKERN_GET_KENEL_DS=0"
		fi
	else
		KERN_DS_UPDATE="-DKERN_GET_KENEL_DS=0"
	fi
	PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_DS_UPDATE "
}

check_kern_modpost ()
{
	if [ -e $SOURCEDIR/scripts/mod/modpost.c ];then
		eval "grep \"is a static \" $SOURCEDIR/scripts/mod/modpost.c | grep error >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_MODPOST_UPDATE="-DKERN_MODPOST_STATIC_ERR=1"
		else
			KERN_MODPOST_UPDATE="-DKERN_MODPOST_STATIC_ERR=0"
		fi
	elif [ -e $DEBSRCDIR/scripts/mod/modpost.c ];then
		eval "grep \"is a static \" $DEBSRCDIR/scripts/mod/modpost.c | grep error >/dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then
			KERN_MODPOST_UPDATE="-DKERN_MODPOST_STATIC_ERR=1"
		else
			KERN_MODPOST_UPDATE="-DKERN_MODPOST_STATIC_ERR=0"
		fi
	else
		KERN_MODPOST_UPDATE="-DKERN_MODPOST_STATIC_ERR=0"
	fi
	PROTOCOL_DEFINES="$PROTOCOL_DEFINES $KERN_MODPOST_UPDATE "
}

# ----------------------------------------------------------------------------
# Display error message.
# ----------------------------------------------------------------------------
error()
{
	echo -e "Error: $*!" >&2
	return 0
}

# ----------------------------------------------------------------------------
# Pause.
# ----------------------------------------------------------------------------
pause()
{

	local force_pause=$1

	if [ -z $force_pause ]; then
		if test $NONINTERACTIVE; then
			return 0
		fi
	else
		shift
	fi

	[ $# -ne 0 ] && echo -e $* >&2
	echo -e "Press [Enter] to continue...\c " >&2
	read tmp
	return 0
}

# ----------------------------------------------------------------------------
# Prompt user for input.
# ----------------------------------------------------------------------------
prompt()
{
	if test $NONINTERACTIVE; then
		return 0
	fi

	echo -ne "$*" >&2
	read CMD rest
	return 0
}

# ----------------------------------------------------------------------------
# Get Yes/No
# ----------------------------------------------------------------------------
getyn()
{
	if test $NONINTERACTIVE; then
		return 0
	fi

	while prompt "$* (y/n) "
	do	case $CMD in
		[yY])	return 0
			;;
		[nN])	return 1
			;;
		*)	echo -e "\nPlease answer y or n" >&2
			;;
		esac
	done
}

# ----------------------------------------------------------------------------
# Select an item from the list.
# Return:	0 - selection is in $SEL
#		1 - quit or empty list
# ----------------------------------------------------------------------------
get_select()
{
	[ $# -eq 0 ] && return 1

	while prompt "Please enter your selection (1..$# or q) ->"
	do	case ${CMD:="0"} in
		[0-9]|[0-9][0-9])
			[ $CMD -lt 1 -o $CMD -gt $# ] && continue
			CMD=`expr $# - $CMD + 1 2>/dev/null`
			until [ $# -eq $CMD ]
			do	shift
			done
			SEL=$1
			return 0
			;;
		q|Q)	return 1
			;;
		esac
	done
}

# ----------------------------------------------------------------------------
# Select an item from the list.
# Return:	0 - selection is in $SEL
#		1 - quit or empty list
# ----------------------------------------------------------------------------
select_list()
{
	[ $# -eq 0 ] && return 1

	col=`expr $# / 10 + 1`
	cnt=0
	for option in $*
	do	cnt=`expr $cnt + 1`
		echo -en "\t$cnt) $option"
		[ `expr $cnt % $col` -eq 0 ] && echo ""
	done
	echo -e "\tq) quit\n"
	get_select $*
}

# ----------------------------------------------------------------------------
# Parse product version.
#	$1	product version X.Y.Z
#
# On exit, environment varibles are set as follows:
#	MAJVER=X
#	MINVER=Y
#	SUBVER=Z
# ----------------------------------------------------------------------------
parse_version()
{
	eval `echo $1 | awk '
		BEGIN	{ FS = "." }
		NR == 1 {
			printf " MAJVER=%s", $1;
			printf " MINVER=%s", $2;
			printf " SUBVER=%s", $3
		}
	'`
}

# ----------------------------------------------------------------------------
# Display banner.
# ----------------------------------------------------------------------------
banner()
{
	if test -z $NONINTERACTIVE; then
	    clearscr
	else
	    echo
	fi

	echo -e "\t----------------------------------------------------------"
	echo -e "\t          WANPIPE v$PROD_VER Installation Script"
	echo -e "\t    Copyright (c) 1995-2013, Sangoma Technologies Inc."
	echo -e "\t----------------------------------------------------------"
	echo ""

	return 0
}

welcome_zaptel()
{

	cat << ENDOFTEXT
${DISTR_NAME} INSTALLATION FOR ZAPTEL

You are about to install ${DISTR_NAME} TDM Voice drivers
for Asterisk/Dahdi/Zaptel framework.

You will be prompted for path to DHADI/ZAPTEL source.

From Zaptel 1.4 and greater or Dahdi:
        wanpipe drivers compile into dahdi/zaptel WITHOUT any
        dahdi/zaptel patching or need to recompile zaptel.
For Zaptel 1.2:
        wanpipe drivers will offer to patch zaptel for DCHAN HDLC
        optimization. Setup will offer you to recompile
        zaptel after patching is complete.

You must have Linux Kernel Headers along with
full development tools (i.e. GNU C compiler and utilities)
installed in order to be able to install this product.

If you have previoulsy installed WANPIPE, this release
will overrite/upgrade full release without the need to
uninstall first!

IMPORTANT:
It is always recommended to say YES to all options
prompted during the install!

Please visit: http://wiki.sangoma.com for more info.

ENDOFTEXT
 
	return
}

welcome_dahdi()
{

	cat << ENDOFTEXT
${DISTR_NAME} INSTALLATION FOR DAHDI

You are about to install ${DISTR_NAME} TDM Voice drivers
for Asterisk/Dahdi framework.

You will be prompted for path to DAHDI source.

Wanpipe drivers will compile into dahdi WITHOUT any
dahdi patching or need to recompile dahdi modules.

You must have Linux Kernel Headers along with
full development tools (i.e. GNU C compiler and utilities)
installed in order to be able to install this product.

If you have previoulsy installed WANPIPE, this release
will overrite/upgrade full release without the need to
uninstall first!

IMPORTANT:
It is always recommended to say YES to all options
prompted during the install!

Please visit: http://wiki.sangoma.com for more info.

ENDOFTEXT
 
	return
}

welcome_default()
{

 cat << ENDOFTEXT
${DISTR_NAME} INSTALLATION

You are about to install ${DISTR_NAME} Multi-Protocol
TDM Voice & WAN Router into your system.

This script will examine your system, then install, create
and/or modify necessary files and directories.

You must have Linux Kernel Headers along with
full development tools (i.e. GNU C compiler and utilities)
installed in order to be able to install this product.

This script will automatically compile all WANPIPE kernel
drivers and install them in their appropriate directory.

If you are installing Wanpipe for ASTERISK/ZAPTEL this
script will will prompt you for zaptel source location.

If you have previoulsy installed WANPIPE, this release
will overrite/upgrade full release without the need to
uninstall first!

IMPORTANT:
It is always recommended to say YES to all options
prompted during the install!

Please visit: http://wiki.sangoma.com for more info.

ENDOFTEXT

	return;


}

# ----------------------------------------------------------------------------
# Show welcome screen.
# ----------------------------------------------------------------------------
welcome()
{
	banner

	if [ "$bri_auto_install" = "YES" ] || [ "$pri_auto_install" = "YES" ]; then
		welcome_default
	elif [ $zaptel_auto_install = "YES" ]; then
		if [ $dahdi_auto_install = "YES" ]; then	
			welcome_dahdi
		else
			welcome_zaptel
		fi
	else 
		welcome_default
	fi

	getyn "Would you like to install WANPIPE now? [y]"
}

# ----------------------------------------------------------------------------
# Goodbye.
# ----------------------------------------------------------------------------
goodbye()
{
	banner

	if test "$DRIVERS_COMPILED" = yes; then

		if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		
			cat <<ENDOFTEXT
WANPIPE (LITE) INSTALLATON: COMPLETE
	
WANPIPE installation is now complete. WANPIPE (LITE) kernel drivers 
and configuration/debug utilities have been compiled and installed.

	1) Proceed to configure the WANPIPE (LITE) drivers using the
	   /usr/sbin/wanhdlc configurator and ifconfig utility. 
	2) To uninstall WANPIPE (LITE) package run ./Setup remove
		
Please read WanpipeInstallation.(pdf/txt) manual for further instructions.

IMPORTANT:
---------
HOTPLUG may conflict with WANPIPE
  Wanpipe interfaces names should be added to the
  HOTPLUG igore list, located in /etc/hotplug/net.agent
  or in /etc/hotplug.d/net.agent file. 
  Please read the ./docs/README.faq for more info.

IMPORTANT: 
---------
The Linux Kernel and Modules in $SOURCEDIR:
	DO NOT have to be manually recompiled!

WANPIPE (LITE) kernel modules are already installed :) 

ENDOFTEXT
			return
		else

			cat <<ENDOFTEXT
WANPIPE INSTALLATON: COMPLETE
	
WANPIPE installation is now complete. WANPIPE kernel drivers 
and configuration/debug utilities have been compiled and installed.

	1) Proceed to configure the WANPIPE drivers:
		Asterisk/Dahdi   : /usr/sbin/wancfg_dahdi
		Asterisk/Zaptel  : /usr/sbin/wancfg_zaptel
		TDM API          : /usr/sbin/wancfg_tdmapi
		SMG SS7/BRI/PRI  : /usr/sbin/wancfg_smg
		WAN Routing/API  : /usr/sbin/wancfg
	2) Use the /usr/sbin/wanrouter startup script to start and stop
	   the router. (eg: wanrouter start)
	3) To uninstall WANPIPE package run ./Setup remove
		
Please read http://wiki.sangoma.com for further instructions.

ENDOFTEXT
		fi

	else

		if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		
			cat <<ENDOFTEXT
WANPIPE (LITE) INSTALLATION: PARTIAL COMPLETE
	
WANPIPE (LITE) utilities and configurators:
	Installed sucessfully.

WANPIPE (LITE) kernel modules:
	FAILED to install or compilation failed.

Please re-run ./Setup install to recompile WANPIPE (LITE) modules.
In case of failure, please contact Sangoma Tech Support.

ENDOFTEXT
		else

			cat <<ENDOFTEXT
WANPIPE INSTALLATION: PARTIAL COMPLETE
	
WANPIPE utilities and configurators:
	Installed sucessfully.

WANPIPE kernel modules:
	Drivers were not installed/compiled

	1) Proceed to configure the WANPIPE drivers:
		Asterisk/Dahdi  : /usr/sbin/wancfg_dahdi
		Asterisk/Zaptel : /usr/sbin/wancfg_zaptel
		SMG SS7/BRI/PRI : /usr/sbin/wancfg_smg
		TDM API         : /usr/sbin/wancfg_tdmapi
		WAN Routing/API : /usr/sbin/wancfg
	2) Use the /usr/sbin/wanrouter startup scrip to start and stop
	   the router. (eg: wanrouter start)
	3) The temporary wanpipe directory can now be deleted
	4) To uninstall WANPIPE package run ./Setup remove
		
Please read http://wiki.sangoma.com for further instructions.

ENDOFTEXT
		fi

	fi
}

# ----------------------------------------------------------------------------
# Prepare for installation.
# ----------------------------------------------------------------------------
prepare()
{
    banner
    # Verify filelist.
    [ -f "$FILELIST" ] || {
		error "File list ($FILELIST) not found"
		return 1
    }

    # Verify files and fix permissions.
	if [ $superuser = "YES" ]; then
		echo "Fixing file permissions..."
		fix_perms || {
			error "Product is not completely installed. Please re-install"
			return 1
		}
	fi

    #Check if wanpipe modules are currently loaded
    eval "lsmod | grep sdladrv > /dev/null"
    if [ $? -eq 0 ]; then
		echo
		echo "Warning: Wanpipe Modules are currently running!"
		echo "Its recommended to unload Wanpipe Modules before proceeding"
		echo "with installation."
		echo
		getyn "\nWould you like to proceed?" || return 1
    fi
    missing_packages=" "
    echo -n "Checking for C developement tools ..."

    check_gcc
    if [ $? -eq 0 ]; then
		echo "($CC) OK"
    else
		echo -e "\n\tWarning: Wanpipe package requires C development tools to complete
								the installation.  Please install development package
								before proceeding. GCC/KGCC/CC compiler not found"
		return 1
    fi

    if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		pause
		return 0
    fi

    echo -n "Checking for C++ developement tools ..."
		eval "g++ --version > /dev/null 2> /dev/null"
    if [ $? -eq 0 ]; then
		echo "OK"
    else
		echo "Failed!"
		missing_packages=$missing_packages"g++ "
    fi

    echo -n "Checking for Make utility ..."
	eval "make --version > /dev/null 2> /dev/null"
	if [ $? -eq 0 ]; then
		echo "OK"
    else
		echo "Failed!"
		missing_packages=$missing_packages"make "
    fi

    echo -n "Checking for ncurses library ... "
    if [ ! -f "/usr/include/ncurses.h" ] && [ ! -f "/usr/include/ncurses/ncurses.h" ]; then
		echo "Failed!"
		missing_packages=$missing_packages"ncurses "
    else
		echo "OK"
    fi

    echo -n "Checking for Perl developement tools ..."
    eval "perl --version 2>/dev/null > /dev/null"
    if [ $? -eq 0 ]; then
		echo "OK"
    else
		echo "Failed!"
		missing_packages=$missing_packages"perl "
    fi

    echo -n "Checking for AWK ..."
    eval "type awk 2> /dev/null > /dev/null"
    if [ $? -eq 0 ]; then
		echo "OK"
    else
		echo "Failed!"
		missing_packages=$missing_packages"awk "
    fi

    echo -n "Checking for FLEX ..."
    eval "type flex 2> /dev/null > /dev/null"
    if [ $? -eq 0 ]; then
		echo "OK"
    else
		echo "Failed!"
		missing_packages=$missing_packages"flex "
    fi

	is_distr_fedora16
	if [ $? -eq 1 ]; then
		flx=`rpm -qa  | grep flex-static`
		if [ "$flx" = "" ]; then
			echo "Failed!"
			missing_packages=$missing_packages"flex-static "
		fi
	fi

    echo -n "Checking for Patch ..."
    eval "patch --version 2> /dev/null > /dev/null"
    if [ $? -eq 0 ]; then
		echo "OK"
    else
		echo "Failed!"
		missing_packages=$missing_packages"patch "
    fi

    echo -n "Checking for libtermcap-devel..."
    if [ -f "/usr/include/termcap.h" ]; then
		echo "OK"
    else
		"Failed!"
		missing_packages=$missing_packages"libtermcap-devel "
    fi

	echo -n "Checking for bison..."
	eval "type bison 2> /dev/null > /dev/null"
	if [  $? -eq 0 ]; then
		echo "OK"
	else
		echo "Failed!"
		missing_packages=$missing_packages"bison "
	fi

	echo -n "Checking for libtool..."
	eval "which libtool 2> /dev/null > /dev/null"
	if [  $? -eq 0 ]; then
		echo "OK"
	else
		echo "Failed!"
		missing_packages=$missing_packages"libtool "
	fi
	
	echo
	if [ ! "$missing_packages" =  " " ]; then
        echo "WARNING: You are missing some prerequisites"
		echo "Missing Packages $missing_packages" >> $CMP_LOG
		for package in $missing_packages
		do
			case $package in
				g++)
					echo -e "\n C++ Compiler (g++)."
					echo -e "    Required for Wanpipe Utilities."
					echo -e "    Install gcc-c++ package (e.g yum install gcc-c++)."
				;;
				make)
					echo -e "\n make utility."
					echo -e "    Required for compiling packages."
					echo -e "    Install make package (e.g yum install make)."
				;;

				bash)
					echo -e "\n Bash v2 or greater."
					echo -e "    Required for wancfg and cfgft1 configuration utilities."
				;;
				ncurses)
					echo -e "\n ncurses library."
					echo -e "    Required for wancfg and cfgft1 configuration utilities."
					echo -e "    Install ncurses development package (e.g yum install ncurses-devel)."
				;;
				perl)
					echo -e "\n Perl development tools."
					echo -e "    Required for Wanpipe package."
					echo -e "    Install ncurses Perl package (e.g yum install perl)."
				;;
				awk)
					echo -e "\n AWK."
					echo -e "    Required for wanrouter startup script."
					echo -e "    Install AWK package (e.g yum install gawk)."
				;;
				patch)
					echo -e "\n Patch ."
					echo -e "    Required for Wanpipe Setup installation script."
					echo -e "    Install Patch package (e.g yum install patch)."
				;;
				libtermcap-devel)
					echo -e "\n Libtermcap development tools ."
					echo -e "    Required for Wanpipe Utilities."
					echo -e "    Install libtermcap-devel package (e.g yum install libtermcap-devel)."
				;;
				flex)
					echo -e "\n Flex package ."
					echo -e "    Required for Wancfg configuration utility."
					echo -e "    Install flex package (e.g yum install flex)."
				;;
				flex-static)
					echo -e "\n flex-static package ."
					echo -e "    Required for Wancfg configuration utility."
					echo -e "    Install flex package (e.g yum install flex-static)."
				;;
				bison)
					echo -e "\n Bison."
					echo -e "    Required for Wanpipe Utilities."
					echo -e "    Install bison package (e.g yum install bison)."
				;;
				libtool)
					echo -e "\n Libtool."
					echo -e "    Required for libsangoma."
					echo -e "    Install libtool package (e.g yum install libtool)."
				;;
				bison)
					echo -e "\n Bison."
					echo -e "    Required for Wanpipe Utilities."
					echo -e "    Install bison package (e.g yum install bison)."
				;;
			esac
		done

		echo
		getyn "Press Y to continue, N to abort installation"
		if [ $? -eq 0 ]; then
			return 0
		else
			echo
			echo "Stopping install per users request"
			echo
			return 1
		fi
    fi

    if [ "$SSMG_BRI" = "YES" ] || [ "$SSMG_PRI" = "YES" ]; then
    	check_sctp_utility
    	find_ast_dirs
    fi

	pause

    return 0
}


# ----------------------------------------------------------------------------
# Verify files and fix permissions.
# ----------------------------------------------------------------------------
fix_perms()
{
	echo -n -e "\nVerifying files and fixing permissions ..."
	
	while read TYPE TARGET MODE OWNER GROUP rest
	do
		[ -z "$TARGET" ] && continue
		[ -z "$MODE" -o -z "$OWNER" -o -z "$GROUP" ] && continue

		#Remove wanpipe/ directory from the 
		#target path, since we are in wanpipe 
		#directory :)

		TARGET=${TARGET#*/}
		
		case $TYPE in
		d)	
			[ -d $TARGET ] || {
				continue
			}
			;;
		f)	
			[ -f $TARGET ] || {
				continue
			}
			;;
		*)	continue
			;;
		esac
		
		echo "chmod $MODE $TARGET" > /dev/null
		chmod $MODE $TARGET
		echo "chown $OWNER $TARGET" > /dev/null
		chown $OWNER $TARGET
		chgrp $GROUP $TARGET
		#echo "Ok."
	done < $FILELIST

	echo "Done";
	return 0
}



apply_pre_211_fix ()
{
	\cp -f $PROD_PATCH/$FIX_211 $SOURCEDIR
	cd $SOURCEDIR
	echo "Patching kernel lower than 2.2.11 !"
	gzip -cd $FIX_211 | patch -p1 || {
		getyn "\nWould you like to continue?" || return 1
		search_rej
		rm $SOURCEDIR/$FIX_211
		return 0
	}
	rm $SOURCEDIR/$FIX_211
}

update_wanpipe_drivers ()
{
	local res=;


	echo
	echo -n "Upgrading ${DISTR_NAME} kernel documentation ..."
	cd $PROD_HOME


	if [ "$PKG_NAME" != "wanpipe-lite" ]; then
		if [ -e $SOURCEDIR/Documentation/networking/wanpipe.txt ]; then
		eval "cp -f README $SOURCEDIR/Documentation/networking/wanpipe.txt"
		fi

		if [ -e $SOURCEDIR/Documentation/networking/wan-router.txt ]; then
		eval "cp -f README $SOURCEDIR/Documentation/networking/wan-router.txt"
		fi	
	fi

	echo -e "Done.\n"
	
	echo
	echo -n "Installing ${DISTR_NAME} include headers ..."

	if [ ! -d $SOURCEDIR/include/linux ]; then
		echo
		echo "ERROR: Directory $SOURCEDIR/include/linux not found!"
		echo "       Corrupted linux headers in $SOURCEDIR dir."
		echo
		return 1
	fi

	eval "./patches/clean_old_wanpipe.sh $DRIVER_INC_DIR $SOURCEDIR/include/linux"

	wan_update_headers;  

	cd $PROD_HOME	
	return 0
}

get_kernel_ver ()
{
	local tmp_ifs=$IFS
	local err=0

	IFS="="
	
	while read name value;
	do
		if [ $AWK_SUPPORT = YES ]; then
			name=`echo $name | awk '{ gsub(" ", "") ; print }'`
		elif [ $BASH_SUPPORT -gt 1 ]; then
			name=${name// /}
		fi

		if [ $AWK_SUPPORT = YES ]; then
			value=`echo $value | awk '{ gsub(" ", "") ; print }'`
		elif [ $BASH_SUPPORT -gt 1 ]; then
			value=${value// /}
		fi

		case $name in

		VERSION)
			KVER=$value
			;;
		PATCHLEVEL)
			KPATCH=$value
			;;
		SUBLEVEL)
			KLVL=$value
			;;
		EXTRAVERSION)
			KEVER=$value
			break
			;;
		esac

	done < $1/Makefile

	KERNEL_VERSION=$KVER"."$KPATCH"."$KLVL$KEVER

	if [ "$KVER" -eq "3" ] || [ "$KVER" -eq "4" ] || [ "$KVER" -eq "5" ]; then
		KERN_VER=30;
		if [ "$KVER" -eq "5" ]; then
			SUBKERN_VER=50;
		elif [ "$KVER" -eq "4" ]; then
			SUBKERN_VER=40;
		else
			SUBKERN_VER=30;
		fi
		LINUXDRIVERS_NET="drivers/net/wan"
	elif [ "$KVER" -eq "2" ] && [ "$KPATCH" -eq "6" ]; then
		KERN_VER=26;
		LINUXDRIVERS_NET="drivers/net/wan"
		KLVL=${KLVL:-6}
	elif [ "$KVER" -eq "2" ] && [ "$KPATCH" -eq "4" ]; then
		KERN_VER=24;
		LINUXDRIVERS_NET="drivers/net/wan"
	elif [ "$KVER" -eq "2" ] && [ "$KPATCH" -eq "2" ]; then
		KERN_VER=22;
		LINUXDRIVERS_NET="drivers/net"
		if [ $ADSL_PROT = YES ];then
			echo "Warning: ADSL driver is only supported on 2.4.X & 2.6.X kernels!"
			ADSL_PROT=NO
		fi
	fi

	#It is possible that we couldn't find the kernel version from the Makefile
	#Possible on SUSE kernels.
	#Use the uname -r info obtained at the begining of the
	#Setup sctipt.

	IFS=$tmp_ifs

	if [ "$DEFAULT_KERNEL_VERSION" = "YES" ]; then
		KERNEL_VERSION=$KERNEL_UNAME
		return;
	fi


	if test -z $NONINTERACTIVE; then

		if [ $KERNEL_VERSION != $KERNEL_UNAME ]; then
			echo 
			echo -e "WARNING: Module installation dir mismatch!"
			echo -e "         Linux source name  = $KERNEL_VERSION"
			echo -e "         Current image name = $KERNEL_UNAME"
			echo
			echo -e "  If you are building wanpipe modules for the"
			echo -e "  currently running image, use the $KERNEL_UNAME"	
			echo -e "  directory (i.e. select 'y') "
			echo
		
				
			getyn "Install modules for current image: $KERNEL_UNAME ?"
			if [ $? -eq 0 ]; then
				KERNEL_VERSION=$KERNEL_UNAME;

				is_distr_fedora2
				if [ $? -eq 1 ]; then
					echo
					echo -e " Fedora2 Update: "
					echo -e "  In order to compile for the current kernel"
					echo -e "  The word 'custom' must be taken out of the"
					echo -e "  $SOURCEDIR/Makefile"
					echo -e "  Then in $SOURCEDIR/ run 'make prepare-all'"
					echo 
					getyn "Would you like us to do it for you ?"
					if [ $? -eq 0 ]; then
						update_kernel_custom_name	
						update_fedora2 0
						if [ $? -ne 0 ]; then
							echo
							echo "Auto configuration failed!"
							echo "Proceed to make above changes manually!"
							echo "Then restart the ./Setup process"
							echo
							pause
							return 1
						fi
					else
						echo
						echo "Proceed to make above changes manually!"
						echo "Then restart the ./Setup process"
						echo
						pause
						return 1	
					fi
				fi
			fi
			echo
			echo "Installing modules for kernel: $KERNEL_VERSION !"
			echo
		fi
	else
		if [ "$WITH_LINUX_OP" = "NO" ]; then
			KERNEL_VERSION=$KERNEL_UNAME
		fi
	fi


	return $err
}


# ----------------------------------------------------------------------------
# Apply kernel patches.
# ----------------------------------------------------------------------------
apply_patches()
{
	local before_14
	local rc

	banner
	cat << ENDOFTEXT

Installing ${DISTR_NAME} Device Drivers: Linux KERNEL

To integrate ${DISTR_NAME} Multi-Protocol Voice & WAN Router 
modules into the Linux kernel, the kernel has to be 
updated with latest wanpipe sources.  Install will only
modify existing wanpipe source that is already in the
Kernel. 

IMPORTANT:
It is always recommended to say YES to all options 
prompted during the install!

ENDOFTEXT

	#getyn "Would you like build wanpipe kernel drivers? [y]" || return 0

	banner

	if [ $WITH_LINUX_OP = NO ]; then
		echo -e "\nPlease specify absolute path name of your linux headers/source directory"
		echo -e "\nPress Enter for Default: $SOURCEDIR\n"
		echo -n "#>"
		if test -z $NONINTERACTIVE; then
			read response

			if test -z $response; then
				DEFAULT_KERNEL_VERSION="YES"
			else
				SOURCEDIR=$response
			fi
		else
			DEFAULT_KERNEL_VERSION="YES"
		fi
	fi

	echo -e "Setting linux directory to $SOURCEDIR\n";
	INCLUDE=$SOURCEDIR/include/linux;


	# Check kernel source directory
	[ -d $SOURCEDIR ] || {
		banner
		cat << ENDOFTEXT
WARNING: Kernel source directory $SOURCEDIR not found!

You may choose to continue installation and then apply patches after
you install kernel source.  To apply patches after ${DISTR_NAME} installation
has been completed run './Setup drivers'. 

ENDOFTEXT

		getyn "Would you like to continue?" || return 1
		return 0
	}
	cd $PROD_HOME/patches

	get_kernel_ver $SOURCEDIR
	if [ $? -eq 1 ]; then
		pause
		return 1;
	fi

	eval "echo "$SOURCEDIR/include" > $PROD_HOME/.sysinclude"
	
	#If the kernel has already been patched, offer an
	#upgrade option.
	check_kernel_patch_level $SOURCEDIR 
	#if [ $? -ne 0 ]; then 
	if [ 1 ]; then
		echo
		#echo "The kernel source in $SOURCEDIR has already been patched!"
		#getyn "Would you like to upgrade ${DISTR_NAME} to the current version ?" || return 0 

		update_wanpipe_drivers
		if [ $? -ne 0 ]; then
			echo "
ERROR: Failed to upgrade ${DISTR_NAME} device drivers!

Make sure that following directories exist: 
	'$SOURCEDIR/$LINUXDRIVERS_WAN' 
	'$SOURCEDIR/$LINUXDRIVERS_NET'
	
Make sure that current kernel image version
matches the kernel version in $SOURCEDIR !!!
	"
			echo
			getyn "Would you like to proceed ?" || return 1
		else
			echo "${DISTR_NAME} device drivers upgraded successfully!"
		fi
		echo
		pause
		return 0;
	fi	

	cd $PROD_HOME/patches

	#-------- Pathching 2.0.X Kernels------------------------
	if [ $KPATCH -eq 0 ]
	then 

		cat <<ENDOFTEXT

WARINIG
-------
Kernel 2.0.X detected!  
This version of wanpipe does not support the 2.0.X kernels.
Please upgrade to 2.2.X or 2.4.X kernels, or use the
older version of wanpipe.

ENDOFTEXT
		return 1;
		
	fi


	#---------- Patching 2.2.X kernels -----------------------
	if [ $KPATCH -eq 2 ]
	then
		#patch a 2.2 kernel
		PATCH=$PROD-v2214.gz
		echo -e "\n\t2.2.X Kernel Detected!\n"

		[ -f $PATCH ] || { getyn "Patch file missing $PATCH, Continue?"; 
				  return; }

		if [ $KLVL -lt 11 ]; then
			apply_pre_211_fix || return 1;
			PATCH=$PROD-v2213.gz

		elif [ $KLVL -lt 14 ]; then
			echo "Patching kernel 2.2.$KLVL."
			PATCH=$PROD-v2213.gz
			
		elif [ $KLVL -eq 14 ]; then
			echo "Patching kernel 2.2.$KLVL."
			PATCH=$PROD-v2214.gz

		elif [ $KLVL -lt 18 ]; then
			echo "Patching kernel 2.2.$KLVL."
			PATCH=$PROD-v2215.gz
			
		elif [ $KLVL -eq 18 ]; then
			echo "Patching kernel 2.2.$KLVL"
			PATCH=$PROD-v2218.gz
		else 
			echo "Patching kernel 2.2.$KLVL"
			PATCH=$PROD-v2219.gz
		fi
	fi

	#----------- Patching 2.4.X Kernels --------------------------------
	if [ $KPATCH -eq 4 ]
	then
		echo -e "\n\t2.4.X Kernel Detected!\n"

		if [ $KLVL -lt 4 ]; then
			PATCH=$PROD-v240.gz
			echo -e "Patching a 2.4.$KLVL Kernel!\n"

		elif [ $KLVL -lt 9 ]; then
			echo "Patching a 2.4.$KLVL Kernel"
			PATCH=$PROD-v244.gz

		elif [ $KLVL -lt 16 ]; then
			echo "Patching a 2.4.$KLVL Kernel"
			PATCH=$PROD-v249.gz
		else 
			echo "Patching a 2.4.$KLVL Kernel"
			PATCH=$PROD-v2416.gz
		fi
	fi


	[ -f $PATCH ] || { getyn "Patch file missing $PATCH, Continue?"; 
			  return; }

	cp $PROD_PATCH/$PATCH $SOURCEDIR
	cd $SOURCEDIR
	gzip -cd $PATCH | patch -p1 || {

		echo "ERROR: Patching failed!"
		echo "The kernel source used is not supported!"
		echo "Call Sangoma at 905-474-1990 or use an older kernel"
		echo
		echo "If the patch failed in the documentation section"
		echo "the failure should be ignored! Thus, proceed with"
		echo "installation."
		echo
		echo "Note, that this kernel patch is only relevant"
		echo "if you are going to recompile the kernel with"
		echo "wanpipe drivers!."
		echo 
		echo "If you are using the ./Setup script to recompile" 
		echo "wanpipe modules, the patch failure can be ignored !"
	
		if test -z $NONINTERACTIVE; then

			rm $SOURCEDIR/$PATCH
			getyn "\nWould you like to continue?" || return 1
		else
			echo 
			echo "Repeat the build procedure to ignore the error!"
			return 1
		fi
	}
	rm $SOURCEDIR/$PATCH

	update_wanpipe_drivers
	if [ $? -ne 0 ]; then
		echo "
ERROR: Failed to patch ${DISTR_NAME} device drivers!

Make sure that following directories exist: 
	'$SOURCEDIR/$LINUXDRIVERS_WAN' 
	'$SOURCEDIR/$LINUXDRIVERS_NET'
	
Make sure that current running kernel image version
matches the kernel version in $SOURCEDIR !!!
	"
		echo
		if test -z $NONINTERACTIVE; then
			getyn "Would you like to proceed ?" || return 1
		else
			return 1
		fi
	else
		echo -e "\nWanpipe drivers patched successfully!\n"
	fi

	# Remove backup files and re-biuld kernel source dependencies.
	cd $SOURCEDIR
	echo "Cleaning up. Please wait..."
	rm -f `find . -name *.orig` 2> /dev/null

	pause
	#search_rej
	return 0
}

# ----------------------------------------------------------------------------
# Install configuration files.
# ----------------------------------------------------------------------------
install_config()
{
	banner

	if [ "$PKG_NAME" = "wanpipe-lite" ]; then

		get_conf_dir

		cat << ENDOFTEXT
WANPIPE (LITE) CONFIGURATION

Please read the wanpipe_lite_manual.(pdf/txt) manual for further
information.

ENDOFTEXT

	else 

		cat << ENDOFTEXT
WANPIPE META CONFIGURATION

There are two configuration files associated with WANPIPE.  

1) $META_CONF: 
	- defines locations of important files such as lock
	  and configuration files as well as start/stop 
	  order of multiple WANPIPE devices.
2) $PROD_CONF:
	- main configuration file for each WANPIPE device.
	- defines interfaces, hardware and protocol information.
	- this file can be created using the 'wancfg' GUI
	  utility or manually based on sample files located
	  in /etc/wanpipe/samples.
	  
Please read the WanpipeInstallation.(pdf/txt) manual for further
information.

ENDOFTEXT
		pause

		# Create meta-configuration file.
		create_mataconf

	fi
	return 0
}


function get_conf_dir ()
{
	local response 

	#banner
	if test -z $NONINTERACTIVE; then
		echo -e "\nPlease specify a desired location for ${DISTR_NAME} configuration files."
		echo -e "\n\t(Press Enter for Default: /etc/wanpipe)\n"
		echo -n "<specify path:>"
		read response

		if [ $response ]; then 
			WAN_CONF_DIR=$response
		else
			WAN_CONF_DIR=/etc/wanpipe
		fi
	else
		WAN_CONF_DIR=/etc/wanpipe
	fi

	if [ ! -d $WAN_CONF_DIR ]; then
		\mkdir -p $WAN_CONF_DIR
	fi

	# Check kernel source directory
	if [ ! -d $WAN_CONF_DIR ]; then
		echo -e "\nERROR: Directory $WAN_CONF_DIR not found !\n"
		getyn "Would you like to try again"
		if [ $? -ne 0 ]; then
			WAN_CONF_DIR=/etc/wanpipe
		else 
			get_conf_dir	
		fi 
	fi
}

function get_bin_dir ()
{
	local response 

	#banner
	if test -z $NONINTERACTIVE; then
		echo -e "\nPlease specify a location for WANPIPE binary, firmware files."
		echo -e "\n\t(Press Enter for Default: /etc/wanpipe/firmware)\n"
		echo -n "<specify path:>"
		read response

		if [ $response ]; then 
			WAN_FIRMWARE_DIR=$response
		else
			WAN_FIRMWARE_DIR=/etc/wanpipe/firmware
		fi
	else
		WAN_FIRMWARE_DIR=/etc/wanpipe/firmware
	fi

	if [ ! -d $WAN_FIRMWARE_DIR ]; then
		\mkdir -p $WAN_FIRMWARE_DIR
	fi

	if [ ! -d $WAN_FIRMWARE_DIR ]; then
		echo -e "\nERROR: Directory $WAN_FIRMWARE_DIR not found !\n"
		getyn "Would you like to try again?"
		if [ $? -ne 0 ]; then
			WAN_FIRMWARE_DIR=/etc/wanpipe/firmware
		else 
			get_bin_dir	
		fi 
	fi
}


function get_intr_dir ()
{
	local response=no
	local response1

	WAN_INTR_DIR=/etc/wanpipe/interfaces

	if [ ! -d $WAN_INTR_DIR ]; then
		\mkdir -p $WAN_INTR_DIR
	fi

#	if [ -d "/etc/sysconfig/network-scripts" ]; then
#		echo -e "\nWould you like to use the NEW network interface types?"
#		echo  	"(RedHat feature:" 
#		echo    "   * Interface files will be written into"
#		echo    "     /etc/sysconfig/network-scripts directory."
#		echo    "   * Interface file names will start with ifcfg-<ifname>"
#		echo    "   * Enables the usage of ifup and ifdown scripts"
#		echo -n "(y/n): "
#		read response
#		case $response in
#			[yY]) WAN_INTR_DIR=/etc/sysconfig/network-scripts
#			      NEW_IF_TYPE=YES;
#			      response=yes
#			;;
#			*)    response=no
#			;;
#		esac
#	fi
#	
#	echo


	if test -z $NONINTERACTIVE; then
		if [ $response = no ]; then

			echo -e "\nPlease specify a desired location for WANPIPE interface files."
			echo -e "\n\t(Press Enter for Default: $WAN_INTR_DIR)\n"
			echo -n "<specify path:>"
			read response1

			WAN_INTR_DIR=/etc/wanpipe/interfaces

			if [ $response1 ]; then 
				WAN_INTR_DIR=$response1
			fi
		fi

		echo

		# Check kernel source directory
		if [ ! -d $WAN_INTR_DIR ]; then
			echo -e "\nERROR: Directory $WAN_INTR_DIR not found !\n"
			getyn "Would you like to try again?"
			if [ $? -ne 0 ]; then
				WAN_INTR_DIR=/etc/wanpipe/interfaces
			else 
				get_intr_dir	
			fi 
		fi
	fi
	
}

# ----------------------------------------------------------------------------
# Create meta-configuration file.
# ----------------------------------------------------------------------------
create_mataconf()
{
	local response

	# Select directory for the log file.
	if	[ -d /var/log ]; then
		LOG_FILE=/var/log/$PROD
	elif	[ -d /var/adm ]; then
		LOG_FILE=/var/adm/$PROD
	else	
		LOG_FILE=/etc/wanpipe/$PROD.log
	fi

	# Select directory for the lock file.
	if	[ -d /var/lock/subsys ]; then
		LOCK_FILE=/var/lock/subsys/$PROD
		LOCK_DIR=/var/lock/subsys
	elif    [ -d /var/lock ]; then
		LOCK_FILE=/var/lock/$PROD
		LOCK_DIR=/var/lock
	else	
		LOCK_FILE=/etc/wanpipe/$PROD.lck
		LOCK_DIR=/etc/wanpipe
	fi


	if [ -f $ROOT/etc/wanpipe/wanrouter.rc ]; then
		. /etc/wanpipe/wanrouter.rc
	fi  

	if [ "$WAN_DEVICES" = "" ]; then
		WAN_DEVICES="wanpipe1"
	else
		echo
		echo "Wanpipe META config file found in /etc/wanpipe directory"
		echo
		echo "Wanpipe startup sequence: $WAN_DEVICES"
		echo
		getyn "Would you like to keep the original wanpipe startup sequence?"
		if [ $? -ne 0 ]; then
			echo 
			echo "New wanpipe startup sequence: wanpipe1"
			WAN_DEVICES="wanpipe1"
		fi
	fi
	
	get_conf_dir
	get_intr_dir

	get_bin_dir

	ENABLE_IP_FWD=NO	

#	cat << EOF
#
#IP Forwarding enables/disables kernel packet routing.
#   If this machine is a router select   Y
#   If this machine is a firewall select N
#
#Note: 
#   If ip forwarding is disabled the kernel will not
#   route packets.  Firewalling policy tables will have
#   to be generaded first.
#
#Options:
#--------
#  Yes: Enable ip forwarding on router startup.
#   No:  Leave ip forwarding unchanged.
#
#EOF
#
#	getyn "Enable IP Forwarding on Wanrouter Startup"
#	if [ $? -ne 0 ]; then
#		ENABLE_IP_FWD=NO
#	else 
#		ENABLE_IP_FWD=YES
#	fi 
#

	if test $NONINTERACTIVE; then
		ENABLE_IP_FWD=NO
	fi

	if [ $ANNEXG_PROT = YES ]; then
		ANNEXG_LOAD=YES;
	fi

	cat > $META_CONF << ENDOFTEXT
#!/bin/bash
# router.rc	WAN router meta-configuration file.
#
#		This file defines variables used by the router shell scripts
#		and should be located in /etc/wanpipe directory.  These are:
#
#               ROUTER_BOOT	=       Boot flag (YES/NO).
#               WAN_CONF_DIR	=       Where to put wanpipe config files.
#		WAN_INTR_DIR	=	Where to put wanpipe interface files.
#               WAN_LOG		=       Where to put start-up log file.
#               WAN_LOCK	=       File used as a lock.
#		WAN_LOCK_DIR	=
#		WAN_IP_FORWARD	=	Enable IP Forwarding on startup.
#               WAN_DEVICES	=       Name of the wanpipe devices to be
#                                       loaded on 'wanrouter start'
#                                       (ex: "wanpipe1 wanpipe2 wanpipe3...")
#
#                              Note:    Name of wanpipe devices correspond
#                                       to the configuration files in
#                                       WANPIPE_CONF_DIR directory:
#                                         (ex. $WAN_CONF_DIR/wanpipe1.conf )
#
#               Note:   This file is 'executed' by the shell script, so
#                       the usual shell syntax must be observed.        
ENDOFTEXT

	echo "ROUTER_BOOT=YES"		>> $META_CONF
	echo "WAN_CONF_DIR=$WAN_CONF_DIR" >> $META_CONF
	echo "WAN_INTR_DIR=$WAN_INTR_DIR" >> $META_CONF
	echo "WAN_BIN_DIR=/usr/sbin"    >> $META_CONF
	echo "WAN_LOG=$LOG_FILE"	>> $META_CONF
	echo "WAN_LOCK=$LOCK_FILE"	>> $META_CONF
	echo "WAN_LOCK_DIR=$LOCK_DIR"	>> $META_CONF
	echo "WAN_IP_FORWARD=$ENABLE_IP_FWD" >> $META_CONF
	echo "NEW_IF_TYPE=$NEW_IF_TYPE" >> $META_CONF
	echo "WAN_LIB_DIR=/etc/wanpipe/lib" >> $META_CONF
	echo "WAN_ADSL_LIST=/etc/wanpipe/wan_adsl.list" >> $META_CONF
	echo "WAN_ANNEXG_LOAD=$ANNEXG_LOAD" >> $META_CONF
	echo "WAN_SCTP_LOAD=$SCTP_LOAD" >> $META_CONF
	echo "WAN_LIP_LOAD=$LIP_LOAD" >> $META_CONF
	echo "WAN_DYN_WANCONFIG=NO" >> $META_CONF
	echo "WAN_SCRIPTS_DIR=/etc/wanpipe/scripts" >> $META_CONF
	echo "WAN_FIRMWARE_DIR=$WAN_FIRMWARE_DIR" >> $META_CONF
	echo "WAN_DEVICES_REV_STOP_ORDER=YES" >> $META_CONF
	echo "WAN_DEVICES=\"$WAN_DEVICES\""	>> $META_CONF

	return 0
}

# ----------------------------------------------------------------------------
#Install initialization scripts.
# ----------------------------------------------------------------------------

install_init()
{
        if [ "$PKG_NAME" = "wanpipe-lite" ]; then
                return 0
        fi

        if [ $NO_AUTO_START -eq 1 ]; then
                return 0;
        fi
        banner
        cat << ENDOFTEXT

WANPIPE BOOTSTRAP CONFIGURATION

Your system uses System V -style initialization scripts.  You have an option
to add router start-up script to those scripts so that the router will start
automatically when system enters multi-user mode and shut down when it enters
single-user mode or when it is halted.

i.e. By selecting this option WANPIPE will startup on system bootup and 
     stop on system shutdown.

ENDOFTEXT

        getyn "Would you like to install WANPIPE start-up scripts?" || return 0

        cd $PROD_HOME/util/wancfg_zaptel
        eval "./wancfg_zaptel.pl --silent --install_boot_script"

        if [ $? -ne 0 ]; then
                echo "Failed to install boot scripts"
        fi

        cd $PROD_HOME

}


# ----------------------------------------------------------------------------
# Old Install initialization scripts.
# ----------------------------------------------------------------------------
install_init_old()
{
	if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		return 0
	fi

	if [ $NO_AUTO_START -eq 1 ]; then
          	return 0;
	fi


	# Examine system bootstrap files.
	if [ -d /etc/rc0.d ]
	then RC_DIR=/etc
	elif [ -d /etc/rc.d/rc0.d ]
	then RC_DIR=/etc/rc.d
	else return 0
	fi

	eval "find $RC_DIR -name 'S*wanrouter' | xargs rm 2> /dev/null"
	eval "find $RC_DIR -name 'K*wanrouter' | xargs rm 2> /dev/null"

	banner
	cat << ENDOFTEXT

WANPIPE BOOTSTRAP CONFIGURATION

Your system uses System V -style initialization scripts.  You have an option
to add router start-up script to those scripts so that the router will start
automatically when system enters multi-user mode and shut down when it enters
single-user mode or when it is halted.

i.e. By selecting this option WANPIPE will startup on system bootup and 
     stop on system shutdown.

ENDOFTEXT

	getyn "Would you like to install WANPIPE start-up scripts?" || return 0

	PROD_INIT=$PROD_INIT$PROD 
	echo -e "\n\t WANPIPE Setup for boot startup "

	if test -z $ROOT; then
		# Install start scripts.
		[ -d $RC_DIR/rc2.d ] && ln -sf $PROD_INIT $RC_DIR/rc2.d/$START_SCRIPT
		[ -d $RC_DIR/rc3.d ] && ln -sf $PROD_INIT $RC_DIR/rc3.d/$START_SCRIPT
		[ -d $RC_DIR/rc4.d ] && ln -sf $PROD_INIT $RC_DIR/rc4.d/$START_SCRIPT
		[ -d $RC_DIR/rc5.d ] && ln -sf $PROD_INIT $RC_DIR/rc5.d/$START_SCRIPT

		# Install stop scripts.
		[ -d $RC_DIR/rc0.d ] && ln -sf $PROD_INIT $RC_DIR/rc0.d/$STOP_SCRIPT
		[ -d $RC_DIR/rc1.d ] && ln -sf $PROD_INIT $RC_DIR/rc1.d/$STOP_SCRIPT
		[ -d $RC_DIR/rc6.d ] && ln -sf $PROD_INIT $RC_DIR/rc6.d/$STOP_SCRIPT
		[ -d $RC_DIR/init.d ] && ln -sf $PROD_INIT $RC_DIR/init.d/$PROD
	else
		# Install start scripts.
		[ -d $RC_DIR/rc2.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$RC_DIR/rc2.d/$START_SCRIPT
		[ -d $RC_DIR/rc3.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$RC_DIR/rc3.d/$START_SCRIPT
		[ -d $RC_DIR/rc4.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$RC_DIR/rc4.d/$START_SCRIPT
		[ -d $RC_DIR/rc5.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL  $ROOT/$RC_DIR/rc5.d/$START_SCRIPT

		# Install stop scripts.
		[ -d $RC_DIR/rc0.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$RC_DIR/rc0.d/$STOP_SCRIPT
		[ -d $RC_DIR/rc1.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$RC_DIR/rc1.d/$STOP_SCRIPT
		[ -d $RC_DIR/rc6.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$RC_DIR/rc6.d/$STOP_SCRIPT
		[ -d $RC_DIR/init.d ] && install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$RC_DIR/init.d/$PROD
	fi

    	if [ "$TDM_PROT" = "YES" ]; then
		getyn "Would you like to auto-execute ztcfg after wanrouter start?" || return 0
			if [ ! -d $WAN_CONF_DIR/scripts ]; then
				eval "\mkdir -p $WAN_CONF_DIR/scripts >/dev/null 2>/dev/null"
			fi 
			eval "\cp -f  $PROD_HOME/samples/wanpipe_zaptel_start $WAN_CONF_DIR/scripts/start >/dev/null 2>/dev/null"
			if [ ! -f $WAN_CONF_DIR/scripts/start ]; then
				echo "Error: Could not copy auto-ztcfg script"
			fi
	fi
	pause
	return 0

}

# ----------------------------------------------------------------------------
# Remove product.
# ----------------------------------------------------------------------------
remove()
{
	banner
	echo "You are about to uninstall WANPIPE package!"
	getyn "\nAre you sure?" || return 0

	# Read meta-configuration file.
	if [ -f $ROUTER_RC ]; then
		source $ROUTER_RC
	fi

#	X25API_CONF=${X25API_CONF:=$X25API_CONF}
	ROUTER_LOG=${ROUTER_LOG:=/var/log/$PROD}
	ROUTER_LOCK=${ROUTER_LOCK:=/var/lock/$PROD}

	[ -f $ROUTER_LOCK ] && {
		error "Wanpipe appears to be running. Stop it first"
		return 1
	}

	if [ -e /proc/net/wanrouter ]; then
      	error "Wanpipe modules are loaded please stop wanpipe fully"
		return 1
	fi

	# Remove wanpipe modules
        echo " "
        echo "Removing Wanpipe modules"
        module_list="sdladrv wanrouter wanpipe_lip wanpipe_syncppp wanpipe af_wanpipe wanec"
        for module_name in $module_list
        do
                eval "modprobe -l |grep $module_name > /dev/null"
                if [ $? -eq 0 ]; then
                        module_path=`modprobe -l |grep $module_name`
                        \rm -f $module_path >/dev/null
                        echo "   $module_path removed"
                else
                        echo "   $module_name module not found"
                fi
        done
        echo "Probing for modules (depmod -a)..."
        eval "depmod -a"


	# Remove start-up scripts.
	remove_init

	# Remove log and configuration files.
	echo "Removing log and configuration files..."
	[ -f $ROUTER_RC ] && rm -f $ROUTER_RC
	[ -f $ROUTER_LOG ] && rm -f $ROUTER_LOG

	#FIXME: Find a better way of doing this
	if [ "$PKG_NAME" != "wanpipe-lite" ]; then
		if  [ -d /etc/wanpipe ]; then
          	rm -rf /etc/wanpipe
		fi
	else
		IFCFG_LIST=`ls /etc/wanpipe/ifcfg-* 2>/dev/null`
		for ifcfg in $IFCFG_LIST; do
			[ -f "$ifcfg" ] && rm -f $ifcfg
		done
	fi

	# Remove contents of the home directory.
	echo -e "\nYou can now delete $PROD_HOME directory and its contents."
	return 0
}

# ----------------------------------------------------------------------------
# Remove initialization scripts.
# ----------------------------------------------------------------------------
remove_init()
{
	# Examine system bootstrap files.
	if [ -d /etc/rc0.d ]
	then RC_DIR=/etc
	elif [ -d /etc/rc.d/rc0.d ]
	then RC_DIR=/etc/rc.d
	else return 0
	fi


	echo "Removing start-up scripts..."
	[ -f $RC_DIR/rc2.d/$START_SCRIPT ] && rm -f $RC_DIR/rc2.d/$START_SCRIPT
	[ -f $RC_DIR/rc3.d/$START_SCRIPT ] && rm -f $RC_DIR/rc3.d/$START_SCRIPT
	[ -f $RC_DIR/rc5.d/$START_SCRIPT ] && rm -f $RC_DIR/rc4.d/$START_SCRIPT
	[ -f $RC_DIR/rc5.d/$START_SCRIPT ] && rm -f $RC_DIR/rc5.d/$START_SCRIPT
	[ -f $RC_DIR/rc0.d/$STOP_SCRIPT  ] && rm -f $RC_DIR/rc0.d/$STOP_SCRIPT
	[ -f $RC_DIR/rc1.d/$STOP_SCRIPT  ] && rm -f $RC_DIR/rc1.d/$STOP_SCRIPT
	[ -f $RC_DIR/rc6.d/$STOP_SCRIPT  ] && rm -f $RC_DIR/rc6.d/$STOP_SCRIPT
	[ -f $RC_DIR/init.d/$PROD  ]       && rm -f $RC_DIR/init.d/$PROD

	eval "find $RC_DIR -name 'S*wanrouter' | xargs rm 2> /dev/null"
	eval "find $RC_DIR -name 'K*wanrouter' | xargs rm 2> /dev/null"
	return 0
}

search_rej ()
{

echo -e "\nLooking for Reject files"
find $SOURCEDIR/. -name '*.rej' > $PROD_HOME/REJECT_FILE
if [ -s $PROD_HOME/REJECT_FILE ]
then
    echo -e "\n!!! Reject Files found: check the  $PROD_HOME/REJECT_FILE !!!"
    echo -e "    WARNING: Patching is not completed"
    echo -e "\n      If the patch version matches the kernel version, there should be "
    echo -e "      no errors, thus copy a fresh kernel into the $SOURCEDIR"
    echo -e "      directory and try again."
    echo -e "\n      If the patch verison is different from the kernel version, check"
    echo -e "      the reject files in $PROD_HOME/REJECT_FILE.  A patch will have"
    echo -e "      to be added in manually. Refer to the README file in "
    echo -e "      ftp.sangoma.com /pub/linux/v2.2.X/(Kernel Version) directory. "
    echo -e "\n      For further assistance email ncorbic@sangoma.com or contact Sangoma"
    echo -e "      at (905) 474 1990.\n"
    pause
else
    echo -e "\n   PATCH SUCCESSFUL:  no reject files found :)\n"
    rm $PROD_HOME/REJECT_FILE  
    pause
fi                         

}

compile_src ()
{
	banner
	if [ "$PKG_NAME" != "wanpipe-lite" ]; then

		cat << ENDOFTEXT
WANPIPE UTILITIES SETUP

WANPIPE utilities are used to:
	1) create configuration files: for Zaptel and Asterisk
		/usr/sbin/wancfg_dahdi	#Dahdi and Asterisk
		/usr/sbin/wancfg_zaptel	#Zaptel and Asterisk
		/usr/sbin/wancfg_smg	#BRI/SS7, Dahdi/Zaptel and Asterisk
		/usr/sbin/wancfg_tdmapi	#TDM API
	2) create WANPIPE WAN/IP configuration files.
		(/usr/sbin/wancfg)
	3) start,stop,restart individual/all devices and interfaces.
		(/usr/sbin/wanrouter)
	4) debug line, protocol and driver problems.
		(/usr/sbin/wanpipemon)
	5) aid in WANPIPE API development
		(/etc/wanpipe/api)

Refer to the WanpipeInstallation.(pdf/txt) for more information.

ENDOFTEXT

		pause
	fi

	[ -d $INCLUDE ] || {
		echo -e "\n\t\tERROR: System environment setup failure !!\n"
		echo -e "\tLinux include directory does not exist: $INCLUDE\n"
		echo -e "\tCompilation process requires the above path"
		echo -e "\tthe $INCLUDE directory must point to the location of the"
		echo -e "\tWANPIPE header files, found in linux source include directory\n"

		echo -e "\tPlease install the Linux source in $SOURCEDIR before"
                echo -e "\tproceeding"
		pause
	       	return 0 
	}

	if [ $KERN_VER -ne 30 ] && [ ! -e $SOURCEDIR/include/asm ]; then
		echo -e "
WARNING: The Linux source in $SOURCEDIR has not been configured [$SOURCEDIR/include/asm].
         Please proceed to configure the source before compiling
         wanpipe utilities (ex: make menuconfig and make dep)."
		echo
		pause
		#return 0
	fi

	if [ ! -e $SOURCEDIR/include/linux/version.h ]; then
		echo -e "
WARNING: The Linux source in $SOURCEDIR has not been configured.
         Please proceed to configure the source before compiling
         wanpipe utilities (ex: make menuconfig and make dep)."
		echo
		pause
		#return 0
	fi


	check_gcc	
	if [ $? -ne 0 ]; then
		echo
		pause
		echo -e "\n\tWarning: Wanpipe package requires C development tools to complete
				      the installation.  Please install development package
				      before proceeding. GCC/KGCC/CC compiler not found"
		return 0
	fi

	delete_old_tools;

	wan_update_headers;
	
	echo -n "Compiling WANPIPE LibSangoma API library ..."

	cd $PROD_HOME/api

	if [ $superuser = "YES" ] && [ -z $ROOT ]; then
		eval "find /usr/local/lib -name 'libsangoma*' > /dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			eval "find /usr/local/lib -name 'libsangoma*' | xargs rm > /dev/null 2>/dev/null"		
			eval "find /usr/local/include -name 'libsangoma*' | xargs rm > /dev/null 2>/dev/null"		
		fi
		eval "find /usr/local/lib -name 'libstelephony*' > /dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			eval "find /usr/local/lib -name 'libstelephony*' | xargs rm > /dev/null 2>/dev/null"		
			eval "find /usr/local/include -name 'libstelephony*' | xargs rm > /dev/null 2>/dev/null"		
		fi
	fi

	cd libsangoma
	eval "./init-automake.sh  >> $CMP_LOG 2>> $CMP_LOG"
	eval "./configure --prefix=/usr >> $CMP_LOG 2>> $CMP_LOG" 
	eval "make clean >> $CMP_LOG 2>> $CMP_LOG" 
	eval "make CC=$CC DESTDIR=$ROOT >> $CMP_LOG 2>> $CMP_LOG" 
	if [ $? -eq 0 ]; then
		echo -e "Done.\n\n"
	else
		echo -e "Failed. \n\n"
		pause
	fi
	eval "make install DESTDIR=$ROOT >> $CMP_LOG 2>> $CMP_LOG"
	
	echo -n "Compiling WANPIPE LibStelephony API library ..."
	
	cd ..
	cd libstelephony
	eval "./init-automake.sh  >> $CMP_LOG 2>> $CMP_LOG"
	eval "./configure --prefix=/usr >> $CMP_LOG 2>> $CMP_LOG" 
	eval "make clean >> $CMP_LOG 2>> $CMP_LOG" 
	eval "make CC=$CC DESTDIR=$ROOT >> $CMP_LOG 2>> $CMP_LOG" 
	if [ $? -eq 0 ]; then
		echo -e "Done.\n\n"
	else
		echo -e "Failed. \n\n"
		pause
	fi
	eval "make install DESTDIR=$ROOT >> $CMP_LOG 2>> $CMP_LOG"
	cd ..

	if [ $superuser = "YES" ] && [ -z $ROOT ]; then
        	eval "ldconfig"
	fi

	cd $PROD_HOME/util

	echo
	echo -n "Compiling ${DISTR_NAME} Utilities ..."

	MAKEINC="PROTOCOL_DEFS=\"$PROTOCOL_DEFINES\""

	if [ $ENABLE_ECHO_DEBUG -eq 1 ]; then
		MAKEINC=$MAKEINC" ENABLE_WANPIPEMON_ZAP=YES " 
	fi

	echo "make CC=$CC SYSINC=$DRIVER_INC_DIR WAN_VIRTUAL=$ROOT WANINCDIR=$WANPIPE_INCLUDE_DIR $MAKEINC" >> $CMP_LOG 2>> $CMP_LOG
	eval "make CC=$CC SYSINC=$DRIVER_INC_DIR WAN_VIRTUAL=$ROOT WANINCDIR=$WANPIPE_INCLUDE_DIR $MAKEINC >> $CMP_LOG 2>> $CMP_LOG"

	if [ $? -eq 0 ]
	then
		echo -e "Done.\n"
	else
		echo
		echo "make CC=$CC SYSINC=$DRIVER_INC_DIR WANINCDIR=$WANPIPE_INCLUDE_DIR $MAKEINC"
		echo
		echo -e "Failed!\n"
		echo -e "\n\t\t!!! ${DISTR_NAME} Tools Compilation Failed !!!"
		echo -e "\tPossible solution:"
		echo -e "\t\t Wanpipe header files were not installed properly"
		echo -e "\t\t in $WANPIPE_INCLUDE_DIR directory"
		echo -e "\tPlease contact Sangoma Tech. at 905 474-1990\n"
		pause
		return 1
	fi


	echo
	echo -n "Compiling ${DISTR_NAME} WanCfg Utility ..."

	WANCFG_DEFS=
	if [ "$TDM_PROT" = "YES" ]; then
		    WANCFG_DEFS=$WANCFG_DEFS" ENABLE_ZAPTEL_PARSER=YES ZAPINC=$ZAPTEL_SOURCE_DIR"
	    if [ -d $ZAPTEL_SOURCE_DIR/dahdi ]; then
		    WANCFG_DEFS=$WANCFG_DEFS" DAHDI_ISSUES=YES"
	#		DAHDI_MAJOR=`cat $ZAPTEL_SOURCE_DIR/dahdi/version.h |  grep define | cut -d'"' -f2 | cut -d'.' -f1`
	#		DAHDI_MINOR=`cat $ZAPTEL_SOURCE_DIR/dahdi/version.h |  grep define | cut -d'"' -f2 | cut -d'.' -f2`
	#		WANCFG_DEFS=$WANCFG_DEFS" -DDAHDI_$DAHDI_MAJOR$DAHDI_MINOR"
	    fi
	fi
	echo "make -C wancfg all CC=$CC WAN_VIRTUAL=$ROOT WANINCDIR=$WANPIPE_INCLUDE_DIR $WANCFG_DEFS" >> $CMP_LOG 2>> $CMP_LOG
	eval "make -C wancfg all CC=$CC WAN_VIRTUAL=$ROOT WANINCDIR=$WANPIPE_INCLUDE_DIR $WANCFG_DEFS >> $CMP_LOG 2>> $CMP_LOG"

	if [ $? -eq 0 ]
	then
		echo -e "Done.\n\n"
	else
		echo
		echo -e "Failed!\n"
		echo -e "\n\t\t!!! ${DISTR_NAME} WanCfg Compilation Failed !!!"
		echo -e "\tPossible solution:"
		echo -e "\t\t FLEX Package not installed"
		echo -e "\t\t Non-standard C/C++ library (eg: ulibc)\n"
		echo -e "\tPlease contact Sangoma Tech. at 905 474-1990\n"
		
		getyn "Proceed with installation without WanCfg ?" || return 1;
	fi

	
	if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		return 0
	fi

	#Disable buld of misc utilities
	#cd $PROD_HOME/util/misc

	#echo -n "Compiling WANPIPE Misc Utilities ..."
	#eval "make CC=$CC WANINCDIR=$WANPIPE_INCLUDE_DIR > /dev/null"
	#echo -e "Done.\n\n"


	if [ $TDM_VOICE_ONLY = 'YES' ]; then
		echo -e "Compiling WANPIPE LibStelephony API Library ... skipped, not required.\n\n"
	else
		if [ -e libstelephony ]; then
			echo -n "Compiling WANPIPE LibStelephony API library ..."
			cd libstelephony
			eval "./init-automake.sh  >> $CMP_LOG 2>> $CMP_LOG"
			eval "./configure --prefix=/usr >> $CMP_LOG 2>> $CMP_LOG" 
			eval "make clean >> $CMP_LOG 2>> $CMP_LOG" 
			eval "make CC=$CC DESTDIR=$ROOT >> $CMP_LOG 2>> $CMP_LOG" 
			if [ $? -eq 0 ]; then
				echo -e "Done.\n\n"
			else
				echo -e "Failed. -- Note this library is not mandatory its safe to continue install \n\n"
				pause
			fi
		fi
	
		eval "make install DESTDIR=$ROOT >> $CMP_LOG 2>> $CMP_LOG"
	
	
		if [ $superuser = "YES" ] && [ -z $ROOT ]; then
			eval "ldconfig > /dev/null 2> /dev/null"
		fi
	fi	

	if [ $TDM_VOICE_ONLY = 'YES' ]; then
		echo -e "Compiling WANPIPE API Development Utilities ... skipped, not required.\n\n"
	else
		echo -n "Compiling WANPIPE API Development Utilities ..."
	
		cd $PROD_HOME/api
	
		if [ -f Makefile ]; then
			eval "make CC=$CC WANINCDIR=$WANPIPE_INCLUDE_DIR >> $CMP_LOG 2>> $CMP_LOG"
			if [ $? -eq 0 ]; then
				echo -e "Done.\n"
			else
				echo -e "Failed!\n"
				echo -e "\tERROR: Failed to compile WANPIPE API Tools !!!"
				echo -e "\tPlease contact support at Sangoma Technologies"
				echo -e "\temail: techdesk@sangoma.com"
				echo -e "\tPlease include the file setup_drv_compile.log\n"
				pause
			fi
		else
			echo -e "Skipped, no makefile\n"
		fi
	fi

	if [ -d $PROD_HOME/util/wanec_client ] && [ -d $DRIVER_UPDATE_DIR/wanec ] ; then
		echo -n "Compiling WANPIPE HWEC Utilities ..."
		cd  $PROD_HOME/util/wanec_client
		eval "make CC=$CC WANINCDIR=$WANPIPE_INCLUDE_DIR WANEC_DIR=$DRIVER_UPDATE_DIR/wanec >> $CMP_LOG 2>> $CMP_LOG "
		if [ $? -eq 0 ]; then
                    echo -e "Done.\n\n"
            	else
                    echo -e "Failed!\n"
                    echo -e "\tERROR: Failed to compile WANPIPE HWEC Tools !!!"
                    echo -e "\tPlease contact support at Sangoma Technologies"
		    echo -e "\temail: techdesk@sangoma.com"
		    echo -e "\tPlease include the file setup_drv_compile.log\n"
                    pause
            	fi
	else
		echo
                echo -n "WANPIPE HWEC Utilities not installed"
		echo
	fi 
	echo -e "\tWANPIPE Environment Setup Complete !!!\n"
	pause
	return 0
}

delete_old_tools()
{
	cd $PROD_HOME/util
	make clean 2> /dev/null > /dev/null

	cd $PROD_HOME
}

check_kernel_patch_level ()
{

	local DIR=$1;
	local val

	if [ -f "$DIR/net/wanrouter/patchlevel" ]; then
		val=`cat $DIR/net/wanrouter/patchlevel`
		#echo -e "\tCurrent WANPIPE kernel patch is $val"
		if [ $val = "2.0.3" ]; then
			return 0
		elif [ $val = "2.2.1" ]; then
			if [ $KPATCH -eq 4 ] && [ $KLVL -gt 3 ]; then
				return 0
			else
				return 1
			fi
		else
			return 1
		fi
	fi

	return 0
}

clean_up ()
{
	[ -f "/usr/sbin/router" ] && rm -f /usr/sbin/router
	
	[ -f $RC_DIR/rc2.d/$OLD_START ] && rm -f $RC_DIR/rc2.d/$OLD_START
	[ -f $RC_DIR/rc3.d/$OLD_START ] && rm -f $RC_DIR/rc3.d/$OLD_START
	[ -f $RC_DIR/rc5.d/$OLD_START ] && rm -f $RC_DIR/rc4.d/$OLD_START
	[ -f $RC_DIR/rc5.d/$OLD_START ] && rm -f $RC_DIR/rc5.d/$OLD_START
	[ -f $RC_DIR/rc0.d/$OLD_STOP ] && rm -f $RC_DIR/rc0.d/$OLD_STOP
	[ -f $RC_DIR/rc1.d/$OLD_STOP ] && rm -f $RC_DIR/rc1.d/$OLD_STOP
	[ -f $RC_DIR/rc6.d/$OLD_STOP ] && rm -f $RC_DIR/rc6.d/$OLD_STOP
	
	[ -f "/etc/router.rc" ] && rm -f /etc/router.rc

}

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

function check_for_af_wanpipe_updates()
{
	if [ $KVER -eq 2 ] && [ $KPATCH -eq 6 ]; then
		if [ $KLVL -eq 11 ]; then
			eval "grep sk_zapped $SOURCEDIR/include/net/sock.h > /dev/null 2> /dev/null"
			if [ $? -ne 0 ]; then
				AF_EXTRA_FLAGS="$AF_EXTRA_FLAGS -DAF_WANPIPE_2612_FORCE_UPDATE "
			fi	
		elif [ $KLVL -gt 11 ]; then
			AF_EXTRA_FLAGS="$AF_EXTRA_FLAGS -DAF_WANPIPE_2612_FORCE_UPDATE "
		fi	
			
		eval "grep CONFIG_NET_NS $SOURCEDIR/include/net/sock.h > /dev/null 2> /dev/null"
		if [ $? -eq 0 ]; then
			AF_EXTRA_FLAGS="$AF_EXTRA_FLAGS -DLINUX_FEAT_CONFIG_NET_NS "
		fi
	fi	
}

function wan_kernel_version_conflict_fix()
{
	local FLAGS=

	if [ $LINUX_VANILLA -gt 0 ]; then
		return;
	fi

	if [ $KVER -eq 2 ] && [ $KPATCH -eq 6 ]; then
		if [ $KLVL -eq 11 ]; then
			if [ "$KEVER" != "" ]; then
				FLAGS="$FLAGS -DAF_WANPIPE_2612_FORCE_UPDATE"
			fi 
		elif [ $KLVL -gt 11 ]; then
			FLAGS="$FLAGS -DAF_WANPIPE_2612_FORCE_UPDATE"
		fi		

		if [ $KLVL -eq 5 ]; then
			if [ "$KEVER" != "" ]; then
				FLAGS="$FLAGS -DWANPIPE_MOD_266_FORCE_UPDATE"
			fi 
		elif [ $KLVL -gt 5 ]; then
			FLAGS="$FLAGS -DWANPIPE_MOD_266_FORCE_UPDATE"
		fi
	fi	

	if [ "$FLAGS" != "" ]; then
		echo "Wan Update Flags: $FLAGS"
		CFLAGS="$CFLAGS $FLAGS "
	fi

}


function is_distr_fedora2()
{
	local distr

	if [ ! -f /etc/issue ]; then
		return 0
	fi
	
	distr=`cat /etc/issue | grep "(Tettnang)"`
	
	#If release is not Fedora2 then
	#get out
	if [ "$distr" = "" ]; then
		return 0
	fi

	return 1
}
function is_distr_fedora16()
{
	local distr

	if [ ! -f /etc/issue ]; then
		return 0
	fi
	
	distr=`cat /etc/issue | grep "(Verne)"`
	
	#If release is not Fedora2 then
	#get out
	if [ "$distr" = "" ]; then
		return 0
	fi

	return 1
}


function update_redhat_as()
{
	local distr
	local rc
	local cmd=$1

	if [ ! -f /etc/issue ]; then
		return 0
	fi
	
	distr=`cat /etc/issue | grep "(Panama)"`
	
	#If release is not RedHat AS then
	#get out
	if [ "$distr" = "" ]; then
		return 0
	fi
	

	if [ ! -f $SOURCEDIR/include/linux/version.h ]; then
		return 0
	fi

	if [ $cmd -eq 0 ]; then

		if [ ! -d /tmp ]; then
			mkdir /tmp
		fi

		\cp -f $SOURCEDIR/include/linux/version.h /tmp/version.h

		rc=`cat /tmp/version.h | awk '{ gsub("132105", "132106") ; print }' > $SOURCEDIR/include/linux/version.h` 
	else
		if [ -f /tmp/version.h ]; then
			\cp -f /tmp/version.h $SOURCEDIR/include/linux/version.h				
		fi
	fi
	return 0;
}

function wan_get_kernel_flags()
{
#	echo "make -C $SOURCEDIR  M=$PWD drivers/net/wan/sdladrv 2> /dev/null"

	if [ ! -d $SOURCEDIR/wanpipe ]; then
		mkdir -p $SOURCEDIR/wanpipe
	fi
	cp $DRIVER_UPDATE_DIR/src/net/sdladrv.c $SOURCEDIR/wanpipe 

	tmp1=`make -C $SOURCEDIR  KBUILD_VERBOSE=0 KBUILD_MODPOST_WARN=1 M=$PWD wanpipe/sdladrv 2> /dev/null`

	#echo "TMP =---$tmp1---"

	tmp=${tmp1#*gcc}

	tmp1=$tmp;

#	echo "TMP1 =---$tmp1---"

	tmp=${tmp1%%wanpipe/*}

	tmp1=$tmp

	tmp=${tmp1%%-m elf*}

	tmp1=$tmp;

	tmp=${tmp1%%-c *};

	tmp1=$tmp;

	tmp=${tmp1//-Iinclude\//-I$WANPIPE_INCLUDE_DIR -I$SOURCEDIR\/include/}

    CFLAGS_EXTRA=$tmp

    if [ $DISABLE_GCC_DEBUG -gt 0 ]; then	
		tmp=${CFLAGS_EXTRA//-g/}
        	CFLAGS_EXTRA=$tmp
	fi

	if [ "$CFLAGS_EXTRA" = "" ]; then
		echo "Major Error: Failed to obtain kernel CFLAGS from $SOURCEDIR"
	fi

	if [ -d $SOURCEDIR/wanpipe ]; then
		\rm -rf $SOURCEDIR/wanpipe
	fi

	eval "echo \"$CFLAGS_EXTRA\" | grep \"mregparm=3\" > /dev/null"
	if [ $? -eq 0 ]; then
		echo "Checking fo regparm: Enabled"
		REGPARM_OPT=".regparm"
	else
		echo "Checking fo regparm: Disabled"
		REGPARM_OPT=""
	fi	

	#echo "CFLAGS_EXTRA=$CFLAGS_EXTRA"

	

	echo
}

function build_kernel_module()
{
	modname=$1
	modfiles=$2
	extra_flags=$3
	local_link=$4
	bin_link=$4
	ofiles=

	extra_flags=$extra_flags" -I/$WANPIPE_INCLUDE_DIR -I$WANPIPE_INCLUDE_DIR/oct6100_api -I$WANPIPE_INCLUDE_DIR/oct6100_api/include -I$WANPIPE_INCLUDE_DIR/oct6100_api/include/oct6100api "

	if [ $KERN_VER -eq 26 ];then
		kernel_version_num=26;
	else 
		if [ $KERN_VER -eq 30 ];then
			kernel_version_num=30;
		fi
	fi

	if [ $KBUILD_DISABLE -ne 1 ] && [ $KERN_VER -eq "$kernel_version_num" ]; then
		for file in $modfiles
		do	
			ofiles=$ofiles"$file.o "
			local_link=$local_link" $file.o "
		done

		echo "make MODULE_NAME=$modname OBJS=\"$ofiles\" M=$PWD CC=$CC KDIR=$SOURCEDIR \
                     EXTRA_CFLAGS=\"-D__LINUX__ $PROTOCOL_DEFINES $extra_flags \"" >> $CMP_BUILD

		chmod 755 $CMP_BUILD
		
		if [ "$CHECK_REGPARM" = "" ]; then
			kverbose=1
		else 
			kverbose=$KBUILD_VERBOSE
		fi

		make MODULE_NAME=$modname OBJS="$ofiles" CC=$CC M=$PWD KBUILD_VERBOSE=$kverbose KBUILD_MODPOST_WARN=1 KDIR=$SOURCEDIR \
                     EXTRA_CFLAGS="-D__LINUX__ $PROTOCOL_DEFINES $extra_flags " >> $CMP_LOG 2>> $CMP_LOG 

		if [ $? -ne 0 ]; then
			echo
			echo "---------------------------------------------"
			echo
			cat $CMP_LOG
			echo
			echo "---------------------------------------------"
			echo
			exit 1;
		else
			if [ $KBUILD_VERBOSE -eq 1 ]; then
			cat $CMP_LOG
			fi
		fi

		if [ "$CHECK_REGPARM" = "" ]; then
			CHECK_REGPARM="done"
			eval "cat $CMP_LOG | grep \"mregparm=3\" > /dev/null"
			if [ $? -eq 0 ]; then
				echo
				echo "Kernel build option regparm: Enabled"
				REGPARM_OPT=".regparm"
			else
				REGPARM_OPT=""
			fi	
		fi

		if [ "$bin_link" != "" ]; then
			
			#echo "----------------------------"
			#echo "ld $LD_ELF -r -o $modname.o $local_link"
			#echo "----------------------------"
			#echo

			echo "ld $LD_ELF -r -o $modname.o $local_link" >> $CMP_BUILD
			$EVALCMD "ld $LD_ELF -r -o $modname.o $local_link"

			#echo "----------------------------"
			#echo "ld $LD_ELF -r -o $modname.ko $modname.o $modname.mod.o"
			#echo "----------------------------"
			#echo 

			rm -f $modname.ko
			rm -f $modname.mod.o

			echo " make MODULE_NAME=$modname OBJS=\"$ofiles\" CC=$CC M=$PWD KBUILD_VERBOSE=$KBUILD_VERBOSE KBUILD_MODPOST_WARN=$KBUILD_MODPOST_WARN KDIR=$SOURCEDIR \
                     	EXTRA_CFLAGS=\"-D__LINUX__ $PROTOCOL_DEFINES $extra_flags \""  >> $CMP_BUILD 

			make MODULE_NAME=$modname OBJS="$ofiles" CC=$CC M=$PWD KBUILD_VERBOSE=$KBUILD_VERBOSE KBUILD_MODPOST_WARN=$KBUILD_MODPOST_WARN KDIR=$SOURCEDIR \
                     	EXTRA_CFLAGS="-D__LINUX__ $PROTOCOL_DEFINES $extra_flags " >> $CMP_LOG 2>> $CMP_LOG 
		#	echo "ld $LD_ELF -r -o $modname.ko $modname.o $modname.mod.o" >> $CMP_BUILD 
		#	$EVALCMD "ld $LD_ELF -r -o $modname.ko $modname.o $modname.mod.o"
		fi

	else	

		for file in $modfiles
		do
		#echo "----------------------------"
		#echo "$CFLAGS $PROTOCOL_DEFINES $extra_flags -DKBUILD_BASENAME=$file -DKBUILD_MODNAME=$modname -c -o tmp/$file.o $file.c"
		#echo "----------------------------"
		#echo

			$EVALCMD "$CFLAGS $PROTOCOL_DEFINES $extra_flags -DKBUILD_BASENAME=$file -DKBUILD_MODNAME=$modname -c -o tmp/$file.o $file.c"
			local_link=$local_link" tmp/$file.o "
		done

		#echo "----------------------------"
		#echo "ld $LD_ELF -r -o mod/$modname.o $local_link"
		#echo "----------------------------"
		#echo
		echo "$EVALCMD \"ld $LD_ELF -r -o mod/$modname.o $local_link\"" >> $CMP_BUILD 
		$EVALCMD "ld $LD_ELF -r -o mod/$modname.o $local_link"

		if [ $KERN_VER -eq 26 ] || [ $KERN_VER -eq 30 ]; then

			#echo "----------------------------"
			#echo "$CFLAGS -DKBUILD_BASENAME=$modname -DKBUILD_MODNAME=$modname -c -o mod/$modname.mod.o $modname.mod.c"
			#echo "----------------------------"
			#echo
			$EVALCMD "$CFLAGS -DKBUILD_BASENAME=$modname -DKBUILD_MODNAME=$modname -c -o mod/$modname.mod.o $modname.mod.c"

			#echo "----------------------------"
			#echo "ld $LD_ELF -r -o mod/$modname.ko mod/$modname.o mod/$modname.mod.o"
			#echo "----------------------------"
			#echo
			$EVALCMD "ld $LD_ELF -r -o mod/$modname.ko mod/$modname.o mod/$modname.mod.o"
		fi

	fi
}


function build_wanec_module ()
{

	local home=`pwd`
	local BTDIR=
	local LARGMATHDIR=
	local LLMANDIR=
	local OCTAPIDIR=
	local OCTAPIMIDIR=
	local EXTRA_FLAGS=
	local files=

	if [ $REL = "3.7" ]; then
		BTDIR=oct61xx/oct6100_api/apilib/bt
		LARGMATHDIR=oct61xx/oct6100_api/apilib/largmath
		LLMANDIR=oct61xx/oct6100_api/apilib/llman
		OCTAPIDIR=oct61xx/oct6100_api/octdeviceapi/oct6100api/oct6100_api
		OCTAPIMIDIR=oct61xx/oct6100_api/octdeviceapi/oct6100api/oct6100_apimi
		OCTAPIXXDIR=oct61xx
		HWECMCDIR=mc    
	else
		BTDIR=oct6100_api/apilib/bt
		LARGMATHDIR=oct6100_api/apilib/largmath
		LLMANDIR=oct6100_api/apilib/llman
		OCTAPIDIR=oct6100_api/octdeviceapi/oct6100api/oct6100_api
		OCTAPIMIDIR=oct6100_api/octdeviceapi/oct6100api/oct6100_apimi
  	fi

	if [ $KERN_VER -eq 24 ]; then 
        	BTDIR=./
		LARGMATHDIR=./
		LLMANDIR=./
		OCTAPIDIR=./ 
		OCTAPIMIDIR=./  	
	fi

	if [ $REL = "3.7" ]; then
 	EXTRA_FLAGS="-I. -I$home -I$home/oct61xx/oct6100_api -I$home/oct61xx/oct6100_api/include -I$home/oct61xx/oct6100_api/include  -I$home/oct61xx/oct6100_api/include/apilib -I$home/oct61xx/oct6100_api/include/apilib -I$home/oct61xx/oct6100_api/include/octrpc -I$home/oct61xx/oct6100_api/include/oct6100api -I$home/oct61xx/oct6100_api/octdeviceapi/oct6100api -DENABLE_TONE_PLAY "
	else
	EXTRA_FLAGS="-I. -I$home -I$home/oct6100_api -I$home/oct6100_api/include -I$home/oct6100_api/include  -I$home/oct6100_api/include/apilib -I$home/oct6100_api/include/apilib -I$home/oct6100_api/include/octrpc -I$home/oct6100_api/include/oct6100api -I$home/oct6100_api/octdeviceapi/oct6100api -DENABLE_TONE_PLAY "
	fi
 					      
 
	if [ $REL = "3.7" ]; then
	files="wanec_main wanec_dev $OCTAPIXXDIR/wanec_oct61xx_main $OCTAPIXXDIR/wanec_oct61xx_cmd $OCTAPIXXDIR/wanec_oct61xx_utils $BTDIR/octapi_bt0 $LARGMATHDIR/octapi_largmath $LLMANDIR/octapi_llman $OCTAPIMIDIR/oct6100_mask_interrupts $OCTAPIDIR/oct6100_adpcm_chan $OCTAPIDIR/oct6100_channel $OCTAPIDIR/oct6100_chip_open $OCTAPIDIR/oct6100_chip_stats $OCTAPIDIR/oct6100_conf_bridge $OCTAPIDIR/oct6100_debug $OCTAPIDIR/oct6100_events $OCTAPIDIR/oct6100_interrupts $OCTAPIDIR/oct6100_memory $OCTAPIDIR/oct6100_miscellaneous  $OCTAPIDIR/oct6100_mixer $OCTAPIDIR/oct6100_phasing_tsst $OCTAPIDIR/oct6100_playout_buf $OCTAPIDIR/oct6100_remote_debug $OCTAPIDIR/oct6100_tlv $OCTAPIDIR/oct6100_tone_detection $OCTAPIDIR/oct6100_tsi_cnct $OCTAPIDIR/oct6100_tsst $OCTAPIDIR/oct6100_user $HWECMCDIR/wanec_mc_main " 
	else
	files="wanec_iface wanec_cmd wanec_utils wanec_dev $BTDIR/octapi_bt0 $LARGMATHDIR/octapi_largmath $LLMANDIR/octapi_llman $OCTAPIMIDIR/oct6100_mask_interrupts $OCTAPIDIR/oct6100_adpcm_chan $OCTAPIDIR/oct6100_channel $OCTAPIDIR/oct6100_chip_open $OCTAPIDIR/oct6100_chip_stats $OCTAPIDIR/oct6100_conf_bridge $OCTAPIDIR/oct6100_debug $OCTAPIDIR/oct6100_events $OCTAPIDIR/oct6100_interrupts $OCTAPIDIR/oct6100_memory $OCTAPIDIR/oct6100_miscellaneous  $OCTAPIDIR/oct6100_mixer $OCTAPIDIR/oct6100_phasing_tsst $OCTAPIDIR/oct6100_playout_buf $OCTAPIDIR/oct6100_remote_debug $OCTAPIDIR/oct6100_tlv $OCTAPIDIR/oct6100_tone_detection $OCTAPIDIR/oct6100_tsi_cnct $OCTAPIDIR/oct6100_tsst $OCTAPIDIR/oct6100_user "   
    fi

	
	eval "make M=$PWD clean >> $CMP_BUILD  2>> $CMP_BUILD "

	if [ $KERN_VER -eq 24 ]; then
        	if [ -e wanectmp ]; then
			eval "rm -rf wanectmp 2>" /dev/null
		fi
		mkdir wanectmp
		eval "\cp -rf $(find . -name '*.*' | xargs) wanectmp/" > /dev/null
		cd wanectmp
		mkdir mod
		mkdir tmp
	fi	

	if [ -e  $PROD_HOME/$MODSYM.wanrouter ]; then
		cat $PROD_HOME/$MODSYM.wanrouter > $MODSYM
	fi
	build_kernel_module wanec "$files" "$EXTRA_FLAGS" 
	if [ $? -ne 0 ]; then
          	return $?;
	fi

        if [ $KERN_VER -eq 24 ]; then
          	cd $home
		if [ -e wanectmp/mod/wanec.o ]; then
                	eval "\cp -f wanectmp/mod/wanec.o ."
		fi
		eval "rm -rf wanectmp"
	fi

	return 0
	
}

function sangoma_64bit_4g_check()
{
	eval "uname -a | grep x86_64" > /dev/null 2> /dev/null	
        if [ $? -ne 0 ] ; then
		val=`cat /proc/meminfo | grep MemTotal | cut -d':' -f2`
		tmp=${val// /}
		b=`expr match "$tmp" '\([0-9]*\)'`
		morethan4bg=`expr $b \> 4000000`
		if [ $morethan4bg -eq 1 ]; then
			#More than 4G of memory
			return 0;
		else
			return 1;
		fi      
	fi                                                            

	#not 64bit 4G mode
        return 1;
}


function create_kernel_mod_file()
{
	local file=$1
	eval "$SOURCEDIR/scripts/mod/modpost -m -i $SOURCEDIR/Module.symvers $file 2> /dev/null 2> /dev/null"
}

function update_kernel_custom_name()
{
	local make_name="fedora2_make"

	if [ ! -f $SOURCEDIR/Makefile ]; then
		echo "Error: File $SOURCEDIR/Makefile not found!"
		return 1;
	fi

	\cp -f $SOURCEDIR/Makefile /tmp/$make_name

	rc=`cat /tmp/$make_name | awk '{ gsub("custom", "") ; print }' > $SOURCEDIR/Makefile` 
	
	cur_home=`pwd`
	cd $SOURCEDIR
	make prepare-all > /dev/null 2> /dev/null
	echo "Kernel name in $SOURCEDIR/Makefile updated successfully ($?)"
	cd $cur_home

	echo
	return 0

}

function update_fedora2()
{
	local distr
	local rc
	local cmd=$1
	local ver_name="fedora2_version.h"

	if [ ! -f /etc/issue ]; then
		return 1
	fi
	
	distr=`cat /etc/issue | grep "(Tettnang)"`
	
	#If release is not Fedora2 then
	#get out
	if [ "$distr" = "" ]; then
		return 1
	fi

	if [ ! -f $SOURCEDIR/include/linux/version.h ]; then
		return 0
	fi

	if [ $cmd -eq 0 ]; then

		if [ ! -d /tmp ]; then
			mkdir /tmp
		fi

		\cp -f $SOURCEDIR/include/linux/version.h /tmp/$ver_name

		rc=`cat /tmp/$ver_name | awk '{ gsub("132613", "132614") ; print }' > $SOURCEDIR/include/linux/version.h` 
	else
		if [ -f /tmp/$ver_name ]; then
			\cp -f /tmp/$ver_name $SOURCEDIR/include/linux/version.h				
		fi
	fi
	return 0;
}


function display_compiled_protocols()
{

	
	if [ $setup_install_quick = "YES" ]; then
		return
	fi

	if [ "$PKG_NAME" != "wanpipe-lite" ]; then
		echo -e "\n\tSupported WAN Protocols:\n"
	fi
	
	if [ $FR_PROT = YES ]; then
	cat << ENDOFTEXT
- Frame Relay 
	Support for frame relay routing, API, or 
	bridging.
ENDOFTEXT
	fi

	if [ $CHDLC_PROT = YES ]; then
	cat << ENDOFTEXT	
- Cisco HDLC 
	Support for Dual Port Cisco HDLC routing 
	API, and TTY PPP over HDLC Streaming on 
	S514-PCI/S508-ISA cards.
ENDOFTEXT
	fi
	
	if [ $PPP_PROT = YES ]; then
	cat << ENDOFTEXT
- PPP
	Support for PPP routing on S514-PCI/S508-ISA cards.
ENDOFTEXT
	fi
	if [ "$PKG_NAME" != "wanpipe-lite" ]; then
		pause
	fi
	echo


	if [ $MPPP_PROT = YES ]; then
	cat << ENDOFTEXT
- Multi Protocol Driver
	Support for kernel RawHDLC/PPP/CHDLC/X25 
	on each Sangoma adapter (S514-PCI/S508-ISE) 
	port PRI and SEC.
ENDOFTEXT
	fi

	if [ $ANNEXG_PROT = YES ]; then
	cat << ENDOFTEXT	
- MP API 
	Support for Kernel LAPB/X25/DSP Protocol Stack. 
	The MP API Stacks can run on both PRI and SEC ports on S514/S508
	adapters. Furthermore, MP API Stacks can be configured
	to run on top of MP Frame Relay or MP Protocol drivers.
ENDOFTEXT
	fi


	if [ $X25_PROT = YES ]; then
	cat << ENDOFTEXT	
- X25 
	Support for X25 routing and API on S514 and S508
	cards.
ENDOFTEXT
	fi

	if [ "$PKG_NAME" != "wanpipe-lite" ] ;then
		cat << ENDOFTEXT
- API Socket
	Support for X25, HDLC, CHDLC and Frame Relay API
	socket development.

ENDOFTEXT
	fi

	pause
	echo
	
	if [ "$BISYNC_PROT" = "YES" ]; then
	cat << ENDOFTEXT

- BiSync API 
	Support for MultiPoint Bisync API on S514 and S508
	cards. Used for connecting to real Bisync network.
ENDOFTEXT
	pause
	echo
	fi

	if [ "$BSCSTRM_PROT" = "YES" ]; then
	cat << ENDOFTEXT

- BiSync Streaming API 
	Support for Bisync Streaming API on S514 and S508
	cards. Used for receiving custom Bisync data via
	custom APIs.
ENDOFTEXT
	pause
	echo
	fi

	if [ "$SS7_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- SS7 Level2 API 
	Support for SS7 Level2 API on S514 and S508
	cards. 
	
ENDOFTEXT
	pause
	echo
	fi
	
	if [ "$ADSL_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- ADSL Protocol
	Support for S518 ADSL cards.
 	Protocols: Ethernet over ATM (LLC/VC) (PPPoE)
	           Classical IP over ATM (LLC/VC)
		   PPP over ATM (LLC/VC)
	Standards: T.413, G.DMT, G.lite ...

ENDOFTEXT
	pause
	echo
	fi


	if [ "$AFT_TE1_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- AFT TE1 Support
	Support for AFT TE1 Cards.
 	Protocols: Frame Relay
	           PPP
		   CHDLC
	API:	   HDLC (Raw)
		   Transparent Bitstreaming

ENDOFTEXT
	pause
	echo
	fi

	if [ "$AFT_TE3_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- AFT TE3 Support
	Support for AFT TE3 Cards.
 	Protocols: Frame Relay
	           PPP
		   CHDLC
	API:	   HDLC (Raw)
		   Transparent Bitstreaming

ENDOFTEXT
	pause
	echo
	fi


	if [ "$ATM_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- ATM Protocol
	Support for AFT and S514-(X) T1/E1/V35 cards.
 	Protocols: Ethernet over ATM (AAL5) (LLC/VC) (PPPoE)
		   PPP over ATM (PPPoA) (LLC/VC) AFT Only
	           Classical IP over ATM (LLC/VC)

ENDOFTEXT
	pause
	echo
	fi

	if [ "$KATM_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- Linux Kernel ATM Stack Protocol
	Support for AFT T1/E1 cards.
 	Protocols: Kernel ATM Stack over AFT ATM (AAL5)

ENDOFTEXT
	pause
	echo
	fi     


	if [ "$XMTP2_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- XMTP2 SS7 Protocol
	Support for LIP XMTP2 AFT cards only.

ENDOFTEXT
	pause
	echo
	fi
	

	
	if [ "$ECHO_MASTER_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- TDMV Echo Detection and Control (EDAC) Feature
	Support for A102/A104 TDMV cards.

ENDOFTEXT
	pause
	echo
	fi


	if [ "$SDLC_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- SDLC API Protocol
	Support for SDLC API protocol on S514/S508 cards.
	
ENDOFTEXT
	pause
	echo
	fi

	if [ "$EDU_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- EDU API Protocol
	Support for Educational Development package over
	S514/S508 cards.
	
ENDOFTEXT
	pause
	echo
	fi

	if [ "$BITSTRM_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- BITSTRM Protocol
	Support for Bitstream Protocol over S514/S508 cards. 
	Bitstream protocol can Tx/Rx data over individual 
	T1/E1 DS0's as well as Tx/Rx raw bit streams.
	
ENDOFTEXT
	pause
	echo
	fi

	if [ "$POS_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- POS S509/S515 Hardware/Protocol Support
	Support for Point of Sale (POS) protocol over  
	S515/S509 cards. Point of Sale protocols include I
	BM 4860, NCR 2126, NCR 1255.
	
ENDOFTEXT
	pause
	echo
	fi

	if [ "$ADCCP_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- ADCCP Lapb API Protocol Support
	Support for ADCCP Lapb API protocol over 
	S514/S508 Cards.
	
ENDOFTEXT
	pause
	echo
	fi

	if [ "$ASYHDLC_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- Async HDLC API Protocol Support
	Support for Async HDLC support over S514/S508 Cards.
	
ENDOFTEXT
	pause
	echo
	fi


	if [ "$TDM_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- TDM Voice Hardware Support for Asterisk PBX Software
	Hardware Support for Asterisk PBX Software over 
	AFT T1/E1 Cards.
	
ENDOFTEXT
	pause
	echo
	fi

	if [ "$XDLC_PROT" = "YES" ]; then
	cat << ENDOFTEXT
	
- XDLC API Support
	LIP XDLC Support
	
ENDOFTEXT
	pause
	echo
	fi

}

function select_compilation_mode()
{
	banner
	local response=
	
	if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_GENERIC "
		return
	fi 

	if [ "$PROTS" != "" ]; then
		#User has already selected protocols on command line
		return;
	fi  

	cat << ENDOFTEXT
	
	Please Select Compilation Mode

1. WAN Protocols Support 
       Protocols: Frame Relay, CHDLC, PPP, ATM, X25, ADSL, TDM API
       Default for: Wan Routing, Data & Voice API devel.

2. Asterisk/Dahdi Support 
       Asterisk protocols: libpri (PRI,BRI), Analog (FXO/FXS), libss7 (SS7)
       Default for: Asterisk 

3. Asterisk/Dahdi + WAN Protocol Support

4. TDM API (libsangoma)  
       Protocols: TDM API (libsangoma) on AFT adapters:
       Default for: FreeSWITCH, Yate, Sunrise
                    Custom voice development 

5. Custom Compilation Mode
       Specify protocols to be added into the WANPIPE
       kernel drivers.

6. Deprecated: SMG (BRI) (Asterisk SMG/BRI [Use Asterisk/Dahdi option 2 instead])

7. Deprecated: SMG (BRI) + Asterisk/Dahdi [Use Asterisk/Dahdi option 2 instead]


ENDOFTEXT

echo -n "Please select (1-7) [Default: 1]: "

if [ -z $NONINTERACTIVE ]; then


	read response

	if [ -z $response ]; then
		response=0
	fi

	if [ "$response"  -eq 1 ]; then
		enable_protocols $DEFAULT_PROTOCOLS

	elif [ "$response"  -eq 2 ]; then
		TDM_VOICE_ONLY=YES
		enable_protocols "TDM"
		enable_protocols "AFT_TE1"
		LIP_PROT=NO
		LIP_LOAD=NO

	elif [ "$response"  -eq 3 ]; then
		enable_protocols "TDM"
		enable_protocols  $DEFAULT_PROTOCOLS
		
	elif [ "$response"  -eq 6 ]; then
		SSMG_BRI=YES
		enable_protocols "AFT_TE1"

	elif [ "$response"  -eq 7 ]; then
		SSMG_BRI=YES
		enable_protocols "AFT_TE1"
		enable_protocols "TDM"

	elif [ "$response"  -eq 4 ]; then
		enable_protocols "AFT_TE1"
		LIP_PROT=NO

	elif [ "$response"  -eq 5 ]; then
		enable_custom_protocols 
	else
		select_compilation_mode
	fi
else
	if [ "$PROTS" = "" ]; then
		if [ $bri_auto_install = "YES" ]; then
			SSMG_BRI=YES
			enable_protocols "BRI"
			enable_protocols "AFT_TE1"
			LIP_PROT=NO
			LIP_LOAD=NO

		elif [ $pri_auto_install = "YES" ]; then
			SSMG_PRI=YES
			enable_protocols "PRI"
			enable_protocols "AFT_TE1"
			LIP_PROT=NO
			LIP_LOAD=NO

		elif [ $zaptel_auto_install = "YES" ]; then
			enable_protocols "TDM"
			enable_protocols "AFT_TE1"
			LIP_PROT=NO
			LIP_LOAD=NO

		else	
			enable_protocols $DEFAULT_PROTOCOLS
		fi	
	fi  

fi
	if [ "$SSMG_SS7" = "YES" ] || [ "$SSMG_BRI" = "YES" ] || [ "$SSMG_PRI" = "YES" ]; then
		check_sctp_utility
		find_ast_dirs
	fi

	return 
}


function makefile_function ()
{
	echo "$1" >> Makefile
}



function wan_update_headers ()
{
	if [ "$WAN_HEADERS_UPDATED" = "YES" ]; then
		#Headers already updated
    	return 0;
	fi

   	cd $DRIVER_UPDATE_DIR/include/     

	if [ -e $WANPIPE_INCLUDE_DIR ]; then
		eval "\rm -rf $WANPIPE_INCLUDE_DIR"
	fi

    eval "\mkdir -p $WANPIPE_INCLUDE_DIR"

	if [ ! -e $WANPIPE_INCLUDE_DIR/linux ]; then
		cd $WANPIPE_INCLUDE_DIR
		ln -s . linux
		ln -s . oct6100_api 
		cd $DRIVER_UPDATE_DIR/include/ 
	fi

	eval "\cp -f *.h $WANPIPE_INCLUDE_DIR/ 2> /dev/null"   
		
	cd $DRIVER_UPDATE_DIR/wanec
	if [ $REL = "3.7" ]; then
	   eval "\cp -rf oct61xx/oct6100_api/include/* $WANPIPE_INCLUDE_DIR/ 2> /dev/null"	
	   eval "\cp -rf *.h $WANPIPE_INCLUDE_DIR/ 2> /dev/null"   
	else
 	   eval "\cp -rf oct6100_api/include/* $WANPIPE_INCLUDE_DIR/ 2> /dev/null"	
	   eval "\cp -rf *.h $WANPIPE_INCLUDE_DIR/ 2> /dev/null"   
	fi
	
	if [ -e $DRIVER_UPDATE_DIR/include/annexg ]; then
		cd $DRIVER_UPDATE_DIR/include/annexg
    	eval "\cp -f *.h $WANPIPE_INCLUDE_DIR/ 2> /dev/null"   
	fi                                

	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		return 1
	fi

	WAN_HEADERS_UPDATED=YES

   	return 0
}



function compile_drivers ()
{

	banner
	if [ "$PKG_NAME" = "wanpipe-lite" ]; then

		cat << ENDOFTEXT
WANPIPE (LITE) KERNEL DRIVER COMPILATION
	
The next step in WANPIPE (LITE) installation involves compiling 
WANPIPE (LITE) kernel module.  

	Therefore, NO kernel recompilation is required :)

WANPIPE (LITE) driver attaches to kernel WAN stacks:
	* Frame Relay
	* PPP
	* Cisco HDLC	
 
Refer to the wanpipe_lite_manual.(pdf/txt) documentation.
ENDOFTEXT

	else
		cat << ENDOFTEXT
WANPIPE KERNEL DRIVER COMPILATION
	
The next step in WANPIPE installation involves compiling 
WANPIPE kernel modules.  

This script will compile and install WANPIPE modules
into the currently running linux kernel.

For greater customization you will be prompted to
select which Protocol/Drivers you would like to
build into the WANPIPE kernel modules.

Wanpipe for Asterisk/Dahdi/Zaptel
	Default for Asterisk/Dahdi/Zaptel
Wanpipe for Wan Routing/API 
	Default for Wan/IP Routing and Data API
Wanpipe for Asterisk SMG/SS7
	Default for Asterisk SS7
Wanpipe for TDM API
	Default for FreeSwitch and Voice API 	

Custom Compilation:
------------------
  Customise WANPIPE driver compilation to add only the
  protocols that you need.  This way one can reduce
  the size of the WANPIPE kernel drivers.

Refer to http://wiki.sangoma.com for more info
ENDOFTEXT
	fi

	if [ -d "$DRIVER_TMP_DIR" ]; then
		rm -rf $DRIVER_TMP_DIR 
	fi

	eval "find $PROD_HOME/ -name \"Module.symvers*\" | xargs \rm -f"

	\mkdir "$DRIVER_TMP_DIR"
	\mkdir "$DRIVER_TMP_DIR/mod"
	\mkdir "$DRIVER_TMP_DIR/tmp"

	get_kernel_ver $SOURCEDIR
	if [ $? -eq 1 ]; then
		pause
		return 1
	fi

	echo
	#getyn "Proceed to build ${DISTR_NAME} kernel modules ? [y]" || return 0;

	if [ ! -d $DRIVER_TMP_DIR ]; then
		eval "\mkdir -p $DRIVER_TMP_DIR > /dev/null"
		if [ $? -ne 0 ]; then
			echo "ERROR: Failed to create $DRIVER_TMP_DIR directory!!!"
			pause
			return 1
		fi
	fi


	ANNEXG_LOAD=NO

	check_gcc	
	if [ $? -ne 0 ]; then
		echo
		pause
		echo -e "\n\tWarning: Wanpipe package requires C development tools to complete
				      the installation.  Please install development package
				      before proceeding. GCC/KGCC/CC compiler not found!"
		return 1
	fi

	if [ ! -f $SOURCEDIR/.config ] && [ -d $SOURCEDIR/configs ]; then

		tmp_k_ver="$KVER"."$KPATCH"."$KLVL"
		tmp_k_arch=`uname -m`
		tmp_smp=`uname -a | grep SMP`
		if [ ! -z $tmp_smp ]; then
			tmp_config_file="kernel-$tmp_k_ver-$tmp_k_arch-smp.config"
		else
			tmp_config_file="kernel-$tmp_k_ver-$tmp_k_arch.config"
		fi	

		if [ -f $SOURCEDIR/configs/$tmp_config_file ] && ! test $NONINTERACTIVE; then

			echo
			echo "	Warning:"
			echo "	The Linux source in $SOURCEDIR doesn't have a .config"
			echo "	file."
			echo
			echo "	Would you like me to configure the Linux source based"
			echo "	on the currently running Linux image: $KERNEL_UNAME"
			echo

			getyn "	Configure the Linux source for $KERNEL_UNAME ?"
			if [ $? -eq 0 ]; then
				tmp_home=`pwd`
				cd $SOURCEDIR
				\cp -f $SOURCEDIR/configs/$tmp_config_file $SOURCEDIR/.config	
				eval "make oldconfig_nonint > /dev/null 2> /dev/null"
				if [ $KERN_VER -eq 26 ] || [ $KERN_VER -eq 30 ]; then
					eval "make prepare0 > /dev/null 2> /dev/null"
				fi
				cd $tmp_home
				echo
				echo "	Linux source config completed successfuly"
				pause
			fi
		fi
	fi



#	if [ ! -d $SOURCEDIR/include/asm ] || [ ! -f $SOURCEDIR/include/linux/autoconf.h ]; then
#		echo -e "\n"
#		echo "ERROR: The $SOURCEDIR contains a fresh, unconfigured kernel!"
#		echo ""
#		echo "       If you already have a working kernel image, a"
#		echo "       simple kernel configuration can solve this problem"
#		echo "	     In linux source dirctory run: "
#		echo 
#		echo "		make dep modules"
#		echo
#		echo "       Then retry the Setup script !!"
#		echo ""
#		echo "       If you are still expriencing problems please contact"
#		echo "       Sangoma Tech Support"
#		pause
#		return 1
#	fi

#	if [ $KERN_VER -ne 26 ] && [ ! -f $SOURCEDIR/include/linux/modversions.h ]; then
#		echo -e "\n"
#		echo "ERROR: The $SOURCEDIR contains a fresh, unconfigured kernel!"
#		echo
#		echo "       If you already have a working kernel image, a"
#		echo "       simple kernel configuration can solve this problem"
#		echo "	     In linux source dirctory run: "
#		echo
#		echo "		make dep modules"
#		echo
#		echo "       Then retry the Setup script !!"
#		echo
#		echo "       If you are still expriencing problems please contact"
#		echo "       Sangoma Tech Support"
#		pause
#		return 1
#	fi

	if [ -e $SOURCEDIR/include/linux/autoconf.h ] || [ -e $SOURCEDIR/include/generated/autoconf.h ]; then 

		if [ -e $SOURCEDIR/include/linux/autoconf.h ]; then
			confdir=include
		else
			confdir=generated
		fi
		eval "grep \"define *CONFIG_WAN_ROUTER *1\" $SOURCEDIR/include/$confdir/autoconf.h > /dev/null"
		if [ $? -eq 0 ]; then
			echo -e "\n"
			echo "ERROR: The ${DISTR_NAME} drivers in $SOURCEDIR have been"
			echo "       configured/compiled into the kernel."
			echo " 	     It's usually recommended that drivers be compiled"
			echo "       as modules."
			echo
			echo "       Please contact Sangoma Tech Support"
			echo
			pause
			return 1
		fi


		eval "grep \"define *CONFIG_MODVERSIONS\" $SOURCEDIR/include/$confdir/autoconf.h > /dev/null"
		if [ $? -eq 0 ]; then
			if [ $KERN_VER -ne 26 ] && [ $KERN_VER -ne 30 ]; then
				MODVER=" -DMODVERSIONS -include $SOURCEDIR/include/linux/modversions.h "
			fi
			MOD_ENABLED=y
		else	
			MODVER=""
			MOD_ENALBED=n
		fi
	else
		MODVER=" -DMODVERSIONS -include $SOURCEDIR/include/linux/modversions.h "
		MOD_ENABLED=y
	fi

	cd $DRIVER_TMP_DIR

	#Copy the WANPIPE device drivers  
	#into a temporary directory

	eval "\cp -f $DRIVER_UPDATE_DIR/src/net/* . >/dev/null 2>/dev/null"
	eval "\cp -f $DRIVER_UPDATE_DIR/src/wanrouter/* .>/dev/null 2>/dev/null"


	eval "\cp -f $PROD_HOME/kbuild/Makefile . >/dev/null 2>/dev/null"

	for file in $DRIVERS_MOD_LIST
	do
		eval "\cp $DRIVER_UPDATE_DIR/src/net/$file . >/dev/null 2>/dev/null" 
	done

	update_redhat_as 0
	update_fedora2   0

	select_compilation_mode

	#display_compiled_protocols

	#Disply all supported protocols that will be compiled
	#into the driver.


	if [ $ANNEXG_PROT = "YES" ]; then
		cp -f $DRIVER_UPDATE_DIR/include/annexg/*.h .
	fi	

	echo
	echo -n "Checking for SMP support ..."
	if [ -e $SOURCEDIR/include/linux/autoconf.h ]; then 
		eval "grep \"CONFIG_SMP *1\" $SOURCEDIR/include/linux/autoconf.h > /dev/null"
		rc=$?
	elif [ -e $SOURCEDIR/include/generated/autoconf.h ]; then 
		eval "grep \"CONFIG_SMP *1\" $SOURCEDIR/include/generated/autoconf.h > /dev/null"
		rc=$?
	else
		rc=0;
	fi
	if [ $rc -eq 0 ]; then
		echo -e "Enabled.\n"
		CONFIG_SMP=YES;
	elif [ $FORCE_SMP ] && [ $FORCE_SMP=YES ]; then
		echo -e "Forced.\n"
		CONFIG_SMP=YES;  
	else	
		echo -e "Disabled.\n"
		eval "uname -a |grep SMP > /dev/null 2> /dev/null"
		if [ $? -eq 0 ]; then
			echo
			echo "   Warning: Current image is configured for SMP"
			getyn "  Would you like to proceed with installation?"
			if [ $? -ne 0 ]; then
				exit 1
			fi 
		fi
		CONFIG_SMP=NO;
	fi

	#Find out our processor type. This is needed to properly
	#compile our modules.
	echo -n "Checking current processor type ..."
	if [ -e $SOURCEDIR/include/linux/autoconf.h ]; then
		grep "CONFIG_ARCH \"" $SOURCEDIR/include/linux/autoconf.h > /dev/null 
		if [ $? -eq 0 ] ; then
			ARCH=`grep "CONFIG_ARCH \"" $SOURCEDIR/include/linux/autoconf.h  | cut -d '"' -f2`
		fi
	fi
	if [ -e $SOURCEDIR/include/generated/autoconf.h ]; then
		grep "CONFIG_ARCH \"" $SOURCEDIR/include/generated/autoconf.h > /dev/null 
		if [ $? -eq 0 ] ; then
			ARCH=`grep "CONFIG_ARCH \"" $SOURCEDIR/include/generated/autoconf.h  | cut -d '"' -f2`
		fi
	fi

	if [ -z $ARCH ]; then
		ARCH=`uname -m`
	fi
	echo -e "$ARCH\n"

	LD_ELF=

	case $ARCH in

	x86_64*) LD_ELF="-m elf_x86_64"
		 ;;
	ia64*)    LD_ELF=" -T $SOURCEDIR/arch/ia64/module.lds "
		 ;;
	i686*)   LD_ELF="-m elf_i386"
			 ARCH=i386
		 ;;
	i586*)   ARCH=i386
		 LD_ELF="-m elf_i386" 
		 ;;
	i486*)   ARCH=i386
		 LD_ELF="-m elf_i386" 
		 ;;
	i386*)   LD_ELF="-m elf_i386" 
		 ;;
	x86*)   LD_ELF="-m elf_i386" 
		 ARCH=i386
		 ;;
	ppc*)
		 ;;
	*)	
		echo "Error: Unsuppored architecture type $ARCH!"
		pause 
		return 1
		;;
	esac
	
	REGPARM_OPT=""

	if [ "$USER_CFLAGS" != "" ]; then
		echo
		echo "Appending User CFLAGS: $USER_CFLAGS"
		echo
	fi

	wan_kernel_version_conflict_fix

	if [ "$USE_CFLAGS" != "" ]; then
		echo
		echo "Compiling with user CFLAGS: $USE_CFLAGS"
		echo
		CFLAGS=$USE_CFLAGS;
	fi

	#Setup the COMPILATOIN FLAGS depending on the kernel type
	if [ $KERN_VER -eq 26 ] || [ $KERN_VER -eq 30 ]; then
		if [ "$USE_CFLAGS" = "" ]; then
CFLAGS="$CC -Wp,-MD,.wanpipe.o.d -nostdinc -iwithprefix include -D__LINUX__ -Dlinux -D__KERNEL__ -I$WANPIPE_INCLUDE_DIR -I$SOURCEDIR/include  -DMODULE $CFLAGS"
			wan_get_kernel_flags
			CFLAGS="$CFLAGS $CFLAGS_EXTRA"
		fi
		
		check_inode_struct

		check_kern_pde_feature

		check_kern_sock_for_feature

		check_kern_netdevice_feature

		check_kern_memcpy_from_msg

		check_kern_memcpy_to_msg

		check_kern_dev_group_struct

		check_kern_timer_struct

		check_kern_refcount_feature

		check_kern_signal_feature

		check_kern_proto_ops_struct

		check_kern_timeofday

		check_kern_ds

		check_kern_modpost

		if [ "$BRI_MODULE_TEST" = "YES" ]; then
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DBUILD_MOD_TESTER"
		fi
		
		if [ 1 -eq 1 ]; then
		echo
		echo "--------------------------------------------------"
		echo "CFLAGS: $CFLAGS"
		echo "--------------------------------------------------"
		echo
		fi


		if [ $KERN_VER -eq 26 ]; then
			echo -n "Compiling General ${DISTR_NAME} Driver for 2.6.X Kernel ."
		else 
			if [ $SUBKERN_VER -eq 40 ]; then
				echo -n "Compiling General ${DISTR_NAME} Driver for 4.X.X Kernel ."
			elif [ $SUBKERN_VER -eq 50 ]; then
				echo -n "Compiling General ${DISTR_NAME} Driver for 5.X.X Kernel ."
			else
				echo -n "Compiling General ${DISTR_NAME} Driver for 3.X.X Kernel ."
			fi
		fi
		
	
	elif [ $KERN_VER -eq 24 ]; then
		echo -n "Compiling General ${DISTR_NAME} Driver for 2.4.X Kernel ."

		if [ "$USE_CFLAGS" = "" ]; then

			case $ARCH in

			x86_64*) 
				CFLAGS="$CC -D__LINUX__ -Dlinux -D__KERNEL__ -I$WANPIPE_INCLUDE_DIR -I$SOURCEDIR/include -Wall -Wstrict-prototypes -Wno-trigraphs -O2 -fno-strict-aliasing -fno-common  -Wno-unused -fomit-frame-pointer -mno-red-zone -mcmodel=kernel -pipe -fno-reorder-blocks -finline-limit=2000 -fno-strength-reduce -fno-asynchronous-unwind-tables   -nostdinc -iwithprefix include -DMODULE -DEXPORT_SYMTAB"
				 ;;

			*)
				if [ $KLVL -lt 32 ]; then  
			       		CFLAGS="$CC -D__LINUX__ -Dlinux -D__KERNEL__ -I$WANPIPE_INCLUDE_DIR -I$SOURCEDIR/include -Wall -Wstrict-prototypes -O2 -fomit-frame-pointer -fno-strict-aliasing -pipe -march=$ARCH -DMODULE -DEXPORT_SYMTAB"
                                else
                                	CFLAGS="$CC -D__LINUX__ -Dlinux -D__KERNEL__ -I$WANPIPE_INCLUDE_DIR -I$SOURCEDIR/include -Wall -Wstrict-prototypes -Wno-trigraphs -O2 -fno-strict-aliasing -fno-common -fomit-frame-pointer -pipe -mpreferred-stack-boundary=2 -march=$ARCH -fno-unit-at-a-time -DMODULE  -nostdinc -iwithprefix include -DMODULE -DEXPORT_SYMTAB"
				fi
				
				#Old gcc do not have this option, thus we must check for it.
				eval "$CC -mpreferred-stack-boundary=2 -S -o /dev/null \
						-xc /dev/null >/dev/null 2>&1" 
				if [ $? -eq 0 ]; then 
					CFLAGS=$CFLAGS" -mpreferred-stack-boundary=2 "
				fi
		
				;;
			esac	

		fi
	else
		echo "ERROR: Unsupported Kernel Version $(uname -r)"
		pause
		return 1
	fi


	if [ $REGPARM_DISABLE -eq 1 ]; then
      	REGPARM_OPT=
	fi

	if [ $CONFIG_SMP = YES -a $KERN_VER -eq 22 ]; then
		CFLAGS=$CFLAGS" -D__SMP__"	
	fi	

	CFLAGS="$CFLAGS $MODVER"

	if [ "$TDM_PROT" = "YES" ]; then
		CFLAGS="$CFLAGS $ASTERISK_IFLAGS"
	fi

	if [ "$USER_CFLAGS" != "" ]; then
		CFLAGS="$CFLAGS $USER_CFLAGS"
	fi

	if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		flag=`grep "cisco_proto" $SOURCEDIR/include/linux/if.h 2> /dev/null`
		if [ -z "$flag" ]; then
			CFLAGS=$CFLAGS" -DOLD_IFSETTINGS_STRUCT"	
		fi 
	fi

	if [ -d "$DRIVER_UPDATE_DIR/wanec" ]; then
       		PROTOCOL_DEFINES=$PROTOCOL_DEFINES" -DCONFIG_WANPIPE_HWEC " 
	fi

	#Compile all individual protocols first
	if [ "$PKG_NAME" = "wanpipe-lite" ]; then

		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=wanpipe_main -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/wanpipe_main.o wanpipe_main.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=wanpipe_hdlc -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/wanpipe_hdlc.o wanpipe_hdlc.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=wanpipe_linux_iface -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/wanpipe_linux_iface.o wanpipe_linux_iface.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdla_56k -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/sdla_56k.o sdla_56k.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdla_te1 -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/sdla_te1.o sdla_te1.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdla_8te1 -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/sdla_8te1.o sdla_8te1.c"  
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdla_te3 -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/sdla_te3.o sdla_te3.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=wanpipe_utils -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/wanpipe_utils.o wanpipe_utils.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdla_abstr -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/wanpipe_abstr.o wanpipe_abstr.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdladrv -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/sdladrv.o sdladrv.c sdladrv_fe.c sdladrv_utils.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdla_xilinx -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/sdla_xilinx.o sdla_xilinx.c"

		if [ $REL = "3.4" ]; then

		 	eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=sdla_aft_te1 -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/sdla_aft_te1.o sdla_aft_te1.c"

		else

			eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=aft_core -DKBUILD_MODNAME=wanpipe_lite \
								  -c -o tmp/aft_core.o aft_core.c"
			eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=aft_core_api_events -DKBUILD_MODNAME=wanpipe_lite \
						   -c -o tmp/aft_core_api_events.o aft_core_api_events.c"
			eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=aft_core_prot -DKBUILD_MODNAME=wanpipe_lite \
						  -c -o tmp/aft_core_prot.o aft_core_prot.c"
			eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=aft_core_utils -DKBUILD_MODNAME=wanpipe_lite \
						   -c -o tmp/aft_core_utils.o aft_core_utils.c"
		fi

		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=aft_a104 -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/aft_a104.o aft_a104.c"
		eval "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=aft_analog -DKBUILD_MODNAME=wanpipe_lite \
				-c -o tmp/aft_analog.o aft_analog.c"

		if [ $? -eq 0 ]; then
			echo -e "Done.\n"
		else
			echo -e "Failed!\n"
		fi

		MEXT=o
		if [ $KERN_VER -eq 26 ] || [ $KERN_VER -eq 30 ]; then
			MEXT=ko
		fi


		if [ $REL = "3.4" ]; then
			eval "ld $LD_ELF -r -o mod/wanpipe_lite.$MEXT tmp/wanpipe_main.o tmp/wanpipe_hdlc.o \
				tmp/wanpipe_linux_iface.o tmp/sdla_te1.o tmp/sdla_8te1.o tmp/sdla_te3.o tmp/sdla_56k.o \
				tmp/wanpipe_utils.o tmp/wanpipe_abstr.o tmp/sdla_xilinx.o tmp/sdla_aft_te1.o \
				tmp/sdladrv.o tmp/aft_a104.o tmp/aft_t116.o tmp/aft_analog.o "

		else
			eval "ld $LD_ELF -r -o mod/wanpipe_lite.$MEXT tmp/wanpipe_main.o tmp/wanpipe_hdlc.o \
				tmp/wanpipe_linux_iface.o tmp/sdla_te1.o tmp/sdla_8te1.o tmp/sdla_te3.o tmp/sdla_56k.o \
			    tmp/wanpipe_utils.o tmp/wanpipe_abstr.o tmp/sdla_xilinx.o \
				tmp/aft_core.o tmp/aft_core_api_events.o tmp/aft_core_prot.o tmp/aft_core_utils.o \
				tmp/sdladrv.o tmp/aft_a104.o tmp/aft_t116.o tmp/aft_analog.o "
		fi

		install -D -m 644 mod/wanpipe_lite.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_lite.$MEXT

# End of LITE 
	else

		if [ 0 -eq 1 ]; then
                echo
                echo "ALLFLAGS"
                echo "--------------------------------------------------"
                echo "$CFLAGS"
                echo "--------------------------------------------------"
                echo
                echo
		fi

	if [ 0 -eq 1 ]; then
	echo
	echo "---------------------------------"
	echo "$CFLAGS $PROTOCOL_DEFINES -DKBUILD_BASENAME=wanmain -DKBUILD_MODNAME=wanrouter -c -o tmp/wanmain.o wanmain.c"
	echo "---------------------------------"
	echo
	fi

cat <<ENDOFTEXT > $PROD_HOME/scripts/Compile_Setup.sh

#!/bin/bash

if [ -e kdrvcmp ]; then
	rm -rf kdrvcmp
fi

mkdir kdrvcmp
cd kdrvcmp
ln -s . common
ln -s . modinfo
mkdir tmp
mkdir mod

cp -f ../patches/kdrivers/src/net/* .
cp -f ../patches/kdrivers/src/wanrouter/* .
cp -f ../patches/kdrivers/src/lip/* .
cp -f ../patches/kdrivers/src/lip/bin/* .
cp -rf ../patches/kdrivers/include/* /usr/src/linux/include/linux
cp -rf ../patches/kdrivers/include/* /usr/include/linux
cp -f ../samples/Makefile .
cp -f ../Compile.sh .

chmod 755 Compile.sh

cd ..

echo "Compile Environmet Setup"

ENDOFTEXT


tmp=${CFLAGS/$CC/}
cat <<ENDOFTEXT > $PROD_HOME/scripts/Compile.sh

#!/bin/bash

make CFLAGS="$tmp"  PROTOCOL_DEFINES="$PROTOCOL_DEFINES"

ENDOFTEXT

tmp=${CFLAGS/$CC/}
cat <<ENDOFTEXT > $PROD_HOME/GCFLAGS
$tmp $PROTOCOL_DEFINES
ENDOFTEXT


EVALCMD=eval
WANPIPE_OBJS=

	rm -f sdladrv_src.c
	ln -s sdladrv.c sdladrv_src.c

	SDLADRV_OBJS="sdladrv_src sdladrv_fe sdladrv_utils wanpipe_cdev_linux wanpipe_logger "

	if [ "$AFT_USB_PROT" = "YES" ]; then
		SDLADRV_OBJS=$SDLADRV_OBJS"sdladrv_usb "
	fi

	build_kernel_module sdladrv "$SDLADRV_OBJS"
	if [ -e $MODSYM ]; then
		cp $MODSYM  $PROD_HOME/$MODSYM.sdladrv 
	fi

	WANROUTER_OBJS="wanmain wanproc waniface "
	if [ $REL != "3.4" ]; then
    	WANROUTER_OBJS=$WANROUTER_OBJS" wandev "  	
	fi

	build_kernel_module wanrouter "$WANROUTER_OBJS"
	if [ -e $MODSYM ]; then
		cp $MODSYM  $PROD_HOME/$MODSYM.wanrouter
	fi

	AF_EXTRA_FLAGS="-DCONFIG_PRODUCT_WANPIPE_SOCK_DATASCOPE"
	check_for_af_wanpipe_updates
	
	rm -f af_wanpipe_src.c
	ln -s af_wanpipe.c af_wanpipe_src.c
	build_kernel_module af_wanpipe "af_wanpipe_src af_wanpipe_datascope" "$AF_EXTRA_FLAGS"
	if [ -e $MODSYM ]; then
		cp $MODSYM  $PROD_HOME/$MODSYM.af_wanpipe 
	fi

	echo -n "."

	if [ "$FR_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_fr "
	fi
	
	if [ "$CHDLC_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_chdlc "
	fi

	if [ "$PPP_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_ppp "
	fi

	echo -n "."

	if [ "$X25_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_x25 "
	fi

	if [ "$MPPP_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"wanpipe_multppp "
		SYNCPPP_PROT=YES
	fi

	if [ "$ANNEXG_PROT" = "YES" ]; then

		#ANNEXG_X25_FLAGS="-DX25_SW -DX25_SWITCH_DEFAULT_API "
		ANNEXG_X25_FLAGS=" "

		for file in $DRIVERS_MPAPI_X25
		do
			\cp $DRIVER_UPDATE_DIR/src/net/annexg/$file .
		done
		for file in $DRIVERS_MPAPI_LAPB
		do
			\cp $DRIVER_UPDATE_DIR/src/net/annexg/$file .
		done
		for file in $DRIVERS_MPAPI_DSP
		do
			\cp $DRIVER_UPDATE_DIR/src/net/annexg/$file .
		done

		build_kernel_module wanpipe_lapb "lapb_iface lapb_in lapb_out lapb_proc lapb_subr lapb_timer lapb_x25_iface"

		build_kernel_module wanpipe_x25 "x25_api_iface x25_dsp_iface x25_facils x25_iface x25_in x25_out x25_proc x25_subr x25_switch x25_timer x25_utils"
	

		build_kernel_module wanpipe_dsp "dsp_api_iface dsp_iface dsp_in dsp_out dsp_proc dsp_subr dsp_timer " 
	fi


		

	if [ "$SS7_PROT" = "YES" ]; then


		\cp $DRIVER_UPDATE_DIR/src/net/sdla_ss7.c .
		if [ "$SS7_USER_ID" = "" ]; then
			echo -e "Failed!\n"
			echo 
			echo "ERROR: SS7 User ID must be suppiled!"
			pause
			return 0
		fi

		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_ss7 "
	fi

	if [ "$EDU_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_edu.c .
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_edu "	
	fi

	if [ "$BISYNC_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_bsc.c .
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_bsc "
		
	fi
	
	if [ "$BSCSTRM_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_bscstrm.c .
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_bscstrm "
	fi

	echo -n "."
	
	if [ "$BITSTRM_PROT" = "YES" ]; then

		\cp $DRIVER_UPDATE_DIR/src/net/sdla_bitstrm.c .

		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_bitstrm "
		SYNCPPP_PROT=YES
	fi
	
	if [ "$ADSL_PROT" = "YES" ]; then

		\cp $DRIVER_UPDATE_DIR/src/net/sdla_adsl.c .

		adsl_file=wanpipe_adsl.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
		if [ ! -e $DRIVER_UPDATE_DIR/src/bin/$adsl_file ]; then
			echo "Warning: ADSL Binary $adsl_file not found!"
			echo "Using wanpipe_adsl.gcc3.i386.o"
			adsl_file=wanpipe_adsl.gcc3.i386.o
		fi

		\cp $DRIVER_UPDATE_DIR/src/bin/$adsl_file tmp/wanpipe_adsl.o
		\cp $DRIVER_UPDATE_DIR/src/bin/$adsl_file wanpipe_adsl.o
		
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_adsl "
		WANPIPE_BIN_OBJS=$WANPIPE_BIN_OBJS"wanpipe_adsl.o "
		SYNCPPP_PROT=YES
	fi

	if [ "$ATM_PROT" = "YES" ]; then

		\cp $DRIVER_UPDATE_DIR/src/net/sdla_atm.c .

		atm_file=wanpipe_atm.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
		if [ ! -e $DRIVER_UPDATE_DIR/src/bin/$atm_file ]; then
			echo "Warning: ATM Binary $atm_file not found!"
			echo "Using wanpipe_atm.gcc3.i386.o"
			atm_file=wanpipe_atm.gcc3.i386.o
		fi

		\cp $DRIVER_UPDATE_DIR/src/bin/$atm_file tmp/wanpipe_atm.o
		\cp $DRIVER_UPDATE_DIR/src/bin/$atm_file wanpipe_atm.o

		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_atm "
		WANPIPE_BIN_OBJS=$WANPIPE_BIN_OBJS"wanpipe_atm.o "

		SYNCPPP_PROT=YES
	fi

	if [ "$ECHO_MASTER_PROT" = "YES" ]; then

		echo_file=wanpipe_edac.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
		if [ ! -e $DRIVER_UPDATE_DIR/src/bin/$echo_file ]; then
			echo "Warning: ECHO MASTER Binary $echo_file not found!"
			echo "Using wanpipe_edac.gcc3.i386.o"
			echo_file=wanpipe_edac.gcc3.i386.o
		fi

		\cp $DRIVER_UPDATE_DIR/src/net/sdla_edac.c .
		\cp $DRIVER_UPDATE_DIR/src/bin/$echo_file tmp/wanpipe_edac.o
		\cp $DRIVER_UPDATE_DIR/src/bin/$echo_file wanpipe_edac.o
		
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_edac "
		WANPIPE_BIN_OBJS=$WANPIPE_BIN_OBJS"wanpipe_edac.o "

	fi

	
	if [ "$SDLC_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_sdlc.c .
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_sdlc "
	fi

	if [ "$POS_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_pos.c .
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_pos "
	fi

	if [ "$ADCCP_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_adccp.c .
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_adccp "
	fi

	if [ "$ASYHDLC_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_asyhdlc.c .
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_asyhdlc "
	fi

	if [ "$TDM_PROT" = "YES" ]; then
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_tdmv.c .
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_remora_tdmv.c .
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_gsm_tdmv.c .
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_bri_tdmv.c .
		\cp $DRIVER_UPDATE_DIR/src/net/sdla_tdmv_dummy.c .
		if [ -e $DRIVER_UPDATE_DIR/src/net/sdla_usb_remora_tdmv.c ]; then
			\cp $DRIVER_UPDATE_DIR/src/net/sdla_usb_remora_tdmv.c .
		fi
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_tdmv sdla_gsm_tdmv sdla_remora_tdmv sdla_bri_tdmv sdla_tdmv_dummy "
		WANPIPE_EXTRA_CFLAGS=$WANPIPE_EXTRA_CFLAGS"-I$ZAPTEL_SOURCE_DIR "
		if [ -f $ZAPTEL_SOURCE_DIR/dahdi/kernel.h ]; then
			# this is required for some dependencies of kernel.h (dahdi_config.h, ecdis.h etc)
			WANPIPE_EXTRA_CFLAGS=$WANPIPE_EXTRA_CFLAGS"-I$ZAPTEL_INSTALL_DIR/drivers/dahdi -I$ZAPTEL_INSTALL_DIR/drivers "
		fi
	fi

	if [ "$AFT_TE1_PROT" = "YES" ]; then
		if [ $REL = "3.4" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_xilinx sdla_aft_te1 aft_a104 aft_t116 sdla_remora aft_analog "
		else 
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_xilinx aft_core aft_core_api_events aft_core_prot aft_core_utils aft_a104 aft_t116 sdla_remora sdla_remora_analog aft_analog wanpipe_timer_dev "

		fi
	fi

	if [ "$AFT_BRI_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_bri aft_bri "
	fi

	if [ "$AFT_USB_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"wanpipe_usb sdla_usb_remora "
		if  [ "$TDM_PROT" = "YES" ]; then
			WANPIPE_OBJS=$WANPIPE_OBJS"sdla_usb_remora_tdmv "
		fi
	fi

	if [ "$AFT_SERIAL_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_serial "
	fi

	if [ "$AFT_TE3_PROT" = "YES" ]; then
		WANPIPE_OBJS=$WANPIPE_OBJS"sdla_aft_te3 "
	fi


	if [ "$SYNCPPP_PROT" = "YES" ]; then
		rm -f wanpipe_syncppp_src.c
		ln -s wanpipe_syncppp.c wanpipe_syncppp_src.c
		build_kernel_module wanpipe_syncppp wanpipe_syncppp_src
		if [ -e $MODSYM ]; then
			cp $MODSYM  $PROD_HOME/$MODSYM.syncppp 
		fi
	fi

	echo -n "."

	WANPIPE_OBJS=$WANPIPE_OBJS"sdla_56k sdla_te1 sdla_8te1 sdla_te3 sdla_ft1 wanpipe_utils wanpipe_abstr wanpipe_linux_iface wanpipe_mtp1 "

	# GSM always built
	WANPIPE_OBJS=$WANPIPE_OBJS"sdla_gsm aft_gsm "
	
	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		return 1
	fi

	if [ "$WAN_FRM_UPDATE_DRIVER" = "YES" ] && 
	   [ -d "$DRIVER_UPDATE_DIR/src/wan_aften" ]; then

		echo
		\cp -f $DRIVER_UPDATE_DIR/src/wan_aften/*.c  .
		\cp -f $DRIVER_UPDATE_DIR/src/wan_aften/*.h  .

		rm -f wan_aften_src.c
		ln -s wan_aften.c wan_aften_src.c
		build_kernel_module wan_aften "wan_aften_src wanpipe_linux_iface"
	fi

	if [ -d "$DRIVER_UPDATE_DIR/wanec" ]; then

		home_tmp=`pwd`
		cd $DRIVER_UPDATE_DIR/wanec
		\cp -f $PROD_HOME/kbuild/Makefile.wanec Makefile		
		build_wanec_module
		if [ $? -eq 0 ]; then
			echo "WAN HWEC module enabled and compiled!"
		else
			echo "WAN HWEC module failed to compile!"
		fi
		if [ -e $MODSYM ]; then
			cp $MODSYM  $PROD_HOME/$MODSYM.wanec
		fi
		cd $home_tmp

	fi

	if [ "$LIP_PROT" = "YES" ]; then

		LIP_LOAD="YES";
		LIP_BIN_OBJS=
		LIP_OBJS=

		echo
		\cp -f $DRIVER_UPDATE_DIR/src/lip/*.c  .
		\cp -f $DRIVER_UPDATE_DIR/src/lip/bin/*.o .

		if [ -e $DRIVER_UPDATE_DIR/src/lip/lip_katm ]; then 
			\cp -f $DRIVER_UPDATE_DIR/src/lip/lip_katm/*.c .
			\cp -f $DRIVER_UPDATE_DIR/src/lip/lip_katm/*.h .
		fi

		if [ -e $DRIVER_UPDATE_DIR/src/lip/lip_hdlc ]; then 
			LIP_HDLC_PROT="YES";
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_LIP_HDLC "  
			\cp -f $DRIVER_UPDATE_DIR/src/lip/lip_hdlc/*.c .
			\cp -f $DRIVER_UPDATE_DIR/src/lip/lip_hdlc/*.h .
		fi

		LIP_LINKED_PROTOCOLS=

		TMP_CFLAGS="-I/$WANPIPE_INCLUDE_DIR -I/ -I$SOURCEDIR/include  -I$SOURCEDIR/include/linux -I../include/common -I../include "
		if [ "$REGPARM_OPT" = ".regparm" ]; then
			TMP_CFLAGS=$TMP_CFLAGS" -mregparm=3 "
		fi

		if [ $FR_PROT = "YES" ]; then
                	 if [ -e $DRIVER_UPDATE_DIR/fr ]; then

                                echo  -n "Compiling Frame Relay sources..."
                                lhome=`pwd`
                                cd $DRIVER_UPDATE_DIR/fr

                                eval "rm -f *.o" >/dev/null 2>/dev/null
				eval "make clean"
                                eval "make all EXTRA_CFLAGS=\" $TMP_CFLAGS \" ARCH=$ARCH " >>$CMP_LOG 2>>$CMP_LOG
                                if [ $? -eq 0 ]; then
                                        echo -e "Done"
                                        echo " "
                                else
                                        echo -e "Failed"
                                        cat $CMP_LOG
                                fi

                                \cp -f wanpipe_fr.o $lhome/wanpipe_fr.o
                                fr_file=wanpipe_fr.o
                                cd $lhome

                        else
                                fr_file=wanpipe_fr.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
                                if [ ! -e $fr_file ]; then
                                        echo "Warning: FR Binary $fr_filenot found!"
                                        echo "Using wanpipe_fr.gcc3.i386.o"
                                        fr_file=wanpipe_fr.gcc3.i386.o
                                fi
                                \cp $fr_file wanpipe_fr.o
                        fi
                        LIP_BIN_OBJS=$LIP_BIN_OBJS"wanpipe_fr.o "
		fi

		if [ $PPP_PROT = "YES" ] || [ $CHDLC_PROT = "YES" ]; then
	       		 if [ -e $DRIVER_UPDATE_DIR/sppp ]; then
                                echo -n "Compiling PPP and CHDLC sources..."
                                lhome=`pwd`
                                cd $DRIVER_UPDATE_DIR/sppp
                                eval "rm -f *.o" >/dev/null 2>/dev/null
				eval "make clean"
                                eval  "make all EXTRA_CFLAGS=\" $TMP_CFLAGS -Iinclude \" ARCH=$ARCH " >>$CMP_LOG 2>>$CMP_LOG
                                if [ $? -eq 0 ]; then
                                        echo -e "Done"
                                        echo " "
                                else
                                        echo -e "Failed"
                                        cat $CMP_LOG
                                fi
                                \cp -f wanpipe_sppp.o $lhome/wanpipe_sppp.o
                                cd $lhome

                                sppp_file=wanpipe_sppp.o
                        else
                                sppp_file=wanpipe_sppp.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
                                if [ ! -e $sppp_file ]; then
                                        echo "Warning: SPPP Binary $sppp_file not found!"
                                        echo "Using wanpipe_sppp.gcc3.i386.o"
                                        sppp_file=wanpipe_sppp.gcc3.i386.o
                                fi
                                \cp $sppp_file wanpipe_sppp.o
                        fi
                        LIP_BIN_OBJS=$LIP_BIN_OBJS"wanpipe_sppp.o "
		fi

		if [ $ATM_PROT = "YES" ]; then
			lip_atm_file=wanpipe_lip_atm.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
			if [ ! -e $lip_atm_file ]; then
				echo "Warning: LIP ATM Binary $lip_atm_file not found!"
				echo "Using wanpipe_lip_atm.gcc3.i386.o"
				lip_atm_file=wanpipe_lip_atm.gcc3.i386.o
			fi
			cp $lip_atm_file wanpipe_lip_atm.o
			LIP_BIN_OBJS=$LIP_BIN_OBJS"wanpipe_lip_atm.o "
		fi

		if [ $LAPB_PROT = "YES" ]; then	
			lapb_file=wanpipe_lapb.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
			if [ ! -e $lapb_file ]; then
				echo "Warning: FR Binary $lapb_file not found!"
				echo "Using wanpipe_lapb.gcc3.i386.o"
				lapb_file=wanpipe_lapb.gcc3.i386.o
			fi
			cp $lapb_file wanpipe_lapb.o	
			LIP_BIN_OBJS=$LIP_BIN_OBJS"wanpipe_lapb.o "
		fi

		if [ $XDLC_PROT = "YES" ]; then

			 if [ -e $DRIVER_UPDATE_DIR/xdlc ]; then
				echo -n "Compiling XDLC sources..."
				lhome=`pwd`
				cd $DRIVER_UPDATE_DIR/xdlc
				eval "rm -f *.o" >/dev/null 2>/dev/null
				eval "make clean"
				eval  "make all EXTRA_CFLAGS=\" $TMP_CFLAGS -Iinclude \" ARCH=$ARCH " >>$CMP_LOG 2>>$CMP_LOG
				if [ $? -eq 0 ]; then
						echo -e "Done"
						echo " "
				else
						echo -e "Failed"
						cat $CMP_LOG
				fi
				\cp -f wanpipe_xdlc.o $lhome/wanpipe_xdlc.o
				cd $lhome

				xdlc_file=wanpipe_xdlc.o
			else
				xdlc_file=wanpipe_xdlc.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
				if [ ! -e $xdlc_file ]; then
					echo "Warning: XDLC Binary $xdlc_file not found!"
					echo "Using wanpipe_xdlc.gcc3.i386.o"
					xdlc_file=wanpipe_xdlc.gcc3.i386.o
				fi
				\cp $xdlc_file wanpipe_xdlc.o
			fi

			LIP_BIN_OBJS=$LIP_BIN_OBJS"wanpipe_xdlc.o "
		fi

		if [ $XMTP2_PROT = "YES" ]; then

			SCTP_LOAD=YES

			xmtp2_file=wanpipe_xmtp2.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
			if [ ! -e $xmtp2_file ]; then
				echo "Warning: FR Binary $xmtp2_file not found!"
				echo "Using wanpipe_xmtp2.gcc3.i386.o"
				xmtp2_file=wanpipe_xmtp2.gcc3.i386.o
			fi
			cp $xmtp2_file wanpipe_xmtp2.o
			LIP_BIN_OBJS=$LIP_BIN_OBJS"wanpipe_xmtp2.o "

			if [ -d xmtp2km ]; then
				rm -rf xmtp2km
			fi

			\cp -rf $DRIVER_UPDATE_DIR/src/xmtp2km .
			cd xmtp2km
			cp ../Makefile .
			ln -s ../mod mod
			ln -s ../tmp tmp

			xmtp2km_file=xmtp2km.gcc$GCC_VER.$ARCH$REGPARM_OPT.o
			if [ ! -e bin/$xmtp2km_file ]; then
				echo "Warning: XMTP2KM Binary $xmtp2km_file not found!"
				xmtp2km_file=xmtp2km.gcc3.i386.o
				echo "Using $xmtp2km_file"
			fi

			XMTP2KM_OBJ="main2_6 fwmsg"

			build_kernel_module xmtp2km "$XMTP2KM_OBJ" "-D__XMTP2__" "bin/$xmtp2km_file" 
			if [ -e $MODSYM ]; then
				cp $MODSYM  $PROD_HOME/$MODSYM.xmtp2 
			fi  

			if [ -e xmtp2km.ko ]; then
				\cp -f xmtp2km.ko ../mod
			fi

			cd ..
		fi
		

		LIP_DEFINES="-DWANLIP_DRIVER -DWPLIP_TTY_SUPPORT"

		lip_src_mods="wanpipe_lip_iface wanpipe_lip_bh wanpipe_lip_prot wanpipe_lip_netdev wanpipe_lip_sub wanpipe_lip_tty wanpipe_abstr wanpipe_linux_iface"
		if [ $KATM_PROT = "YES" ]; then
                	lip_src_mods=$lip_src_mods" wanpipe_katm_iface wanpipe_katm_sub"
		fi
		if [ $LIP_HDLC_PROT = "YES" ]; then
                	lip_src_mods=$lip_src_mods"  wanpipe_hdlc_iface wanpipe_hdlc_eng"
		fi

		if [ -e  $PROD_HOME/$MODSYM.xmtp2 ]; then
			cat $PROD_HOME/$MODSYM.xmtp2 >> $MODSYM
		fi  

		build_kernel_module wanpipe_lip "$lip_src_mods" "$LIP_DEFINES" "$LIP_BIN_OBJS" 
        if [ -e $MODSYM ]; then
			cp $MODSYM  $PROD_HOME/$MODSYM.lip 
		fi 

		if [ $FR_PROT = "YES" ]; then
		echo "FR compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$fr_file"
		echo
		fi
		if [ $PPP_PROT = "YES" ] || [ $CHDLC_PROT = "YES" ]; then
		echo "PPP/CHDLC compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$sppp_file"
		echo
		fi
		if [ $LAPB_PROT = "YES" ]; then
		echo "Lapb compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$lapb_file"
		echo
		fi
		if [ $XDLC_PROT = "YES" ]; then
		echo "Xdlc compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$xdlc_file"
		echo
		fi
		if [ $ATM_PROT = "YES" ]; then
		echo "ATM compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$lip_atm_file"
		echo
		fi
		if [ $XMTP2_PROT = "YES" ]; then
		echo "XMTP2 compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$xmtp2_file"
		echo
		fi
	fi


	if [ "$ADSL_PROT" = "YES" ]; then
		echo "ADSL binary compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$adsl_file"
		echo
	fi

	if [ "$ATM_PROT" = "YES" ]; then
		echo "ATM binary compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$atm_file"
		echo
	fi

	if [ "$ECHO_MASTER_PROT" = "YES" ]; then
		echo "TDMV Echo Detection (EDAC) binary compiled for GCC Ver=$GCC_VER Arch=$ARCH File:$echo_file"
		echo
	fi


	echo -n "Linking Wanpipe Driver and protocols ..."	

	#Link in appropriate protocols as needed.
	if [ -e $MODSYM ]; then
		eval "\rm -f $MODSYM"
	fi

	if [ "$TDM_PROT" = "YES" ]; then
		if [ -f $ZAPTEL_SYM_DIR/$MODSYM ]; then
			cat $ZAPTEL_SYM_DIR/$MODSYM >> $MODSYM
		fi
	fi

	if [ -f  $PROD_HOME/$MODSYM.wanec ]; then
		cat $PROD_HOME/$MODSYM.wanec >> $MODSYM
	fi
	if [ -f $PROD_HOME/$MODSYM.syncppp ]; then
		cat $PROD_HOME/$MODSYM.syncppp >> $MODSYM
	fi
	if [ -e  $PROD_HOME/$MODSYM.xmtp2 ]; then
		cat $PROD_HOME/$MODSYM.xmtp2 >> $MODSYM
	fi
	if [ -e  $PROD_HOME/$MODSYM.lip ]; then
		cat $PROD_HOME/$MODSYM.lip >> $MODSYM
	fi

	WANPIPE_OBJS=$WANPIPE_OBJS"sdlamain wanpipe_tdm_api wanpipe_codec wanpipe_codec_law " 
	build_kernel_module wanpipe "$WANPIPE_OBJS" "$WANPIPE_EXTRA_CFLAGS" "$WANPIPE_BIN_OBJS" 
	

	\cp -f *.ko mod/  > /dev/null 2> /dev/null
	
	MEXT=o
	if [ $KERN_VER -eq 26 ] || [ $KERN_VER -eq 30 ]; then
		MEXT=ko
	fi

	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		return 1
	fi

	update_redhat_as 1
	update_fedora2   1

	wp_comp_err=0;
	if [ ! -e mod/sdladrv.$MEXT ]; then
		echo "Compilation Error: Module sdladrv.$MEXT not found!"
		wp_comp_err=1;
	fi
	if [ ! -e mod/wanpipe.$MEXT ]; then
		echo "Compilation Error: Module mod/wanpipe.$MEXT not found!"
		wp_comp_err=1;
	fi
	if [ ! -e mod/wanrouter.$MEXT ]; then
		echo "Compilation Error: Module mod/wanrouter.$MEXT not found!"
		wp_comp_err=1;
	fi
	if [ ! -e mod/af_wanpipe.$MEXT ]; then
		echo "Compilation Error: Module mod/af_wanpipe.$MEXT not found!"
		wp_comp_err=1;
	fi	
	if [ "$LIP_PROT" = "YES" ] && [ ! -e mod/wanpipe_lip.$MEXT ]; then
		echo "Compilation Error: Module mod/wanpipe_lip.$MEXT not found!"
		wp_comp_err=1;
	fi

	if [ "$XMTP2_PROT" = "YES" ] && [ ! -e mod/xmtp2km.$MEXT ]; then
		echo "Compilation Error: Module mod/xmtp2km.$MEXT not found!"
		wp_comp_err=1;
	fi

	

	if [ $wp_comp_err -eq 1 ]; then
		echo
		echo "Wanpipe drivers failed to compile"
		echo "Please review the above error messages"
		echo "and/or contact Sangoma Tech Support."
		echo
		return 1
	fi

	#Copy the newly compiled modules into the /lib/modules directory.
	
	echo -n "Updating Kernel Modules ..."

	if [ $KERN_VER -eq 24 ] || [ $KERN_VER -eq 26 ] || [ $KERN_VER -eq 30 ]; then

	   eval "\rm -f $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/sdladrv.$MEXT* > /dev/null 2> /dev/null"
	   eval "\rm -f $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe.$MEXT* > /dev/null 2> /dev/null"
	   eval "\rm -f $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_syncppp.$MEXT* > /dev/null 2> /dev/null"
	   
	   eval "\rm -f $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wan_aften.$MEXT* > /dev/null 2> /dev/null"
	   eval "\rm -f $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanrouter.$MEXT* > /dev/null 2> /dev/null"
	   eval "\rm -f $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/af_wanpipe.$MEXT* > /dev/null 2> /dev/null"
	   eval "\rm -f $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanpipe_lip.$MEXT* > /dev/null 2> /dev/null" 

	   install -D -m 644 mod/sdladrv.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/sdladrv.$MEXT
	   install -D -m 644 mod/wanpipe.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe.$MEXT
	   install -D -m 644 mod/wanrouter.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanrouter.$MEXT
	   install -D -m 644 mod/af_wanpipe.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/af_wanpipe.$MEXT

	   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
		echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/sdladrv.$MEXT" | xargs gzip -f9
	   	echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe.$MEXT" | xargs gzip -f9
	   	echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanrouter.$MEXT" | xargs gzip -f9
	   	echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/af_wanpipe.$MEXT" | xargs gzip -f9
	   fi
 
	   if [ -f mod/wanpipe_syncppp.$MEXT ]; then
		   install -D -m 644 mod/wanpipe_syncppp.$MEXT   $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_syncppp.$MEXT 
		   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
		   	echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_syncppp.$MEXT" | xargs gzip -f9
		   fi
	   fi

	   if [ -f mod/wan_aften.$MEXT ]; then
	       	   install -D -m 644 mod/wan_aften.$MEXT   $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wan_aften.$MEXT 
		   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
	  		 echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wan_aften.$MEXT" | xargs gzip -f9 
		   fi
	   fi


	   if [ -d "$DRIVER_UPDATE_DIR/wanec" ]; then
           	install -D -m 644 $DRIVER_UPDATE_DIR/wanec/wanec.$MEXT   $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanec.$MEXT
		if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
                      echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanec.$MEXT" | xargs gzip -f9
                fi
           fi

	   if [ -f mod/wanpipe_x25.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_x25.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_x25.$MEXT
		   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
	   		echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_x25.$MEXT" |xargs gzip -f9
		   fi
	   fi
	   if [ -f mod/wanpipe_lapb.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_lapb.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_lapb.$MEXT
		   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
	  		echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_lapb.$MEXT" |xargs gzip -f9
		   fi
	   fi
	   if [ -f mod/wanpipe_dsp.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_dsp.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_dsp.$MEXT
		   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
	   		echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_dsp.$MEXT" |xargs gzip -f9
		   fi
	   fi

	   if [ -f mod/xmtp2km.$MEXT ]; then
	   install -D -m 644 mod/xmtp2km.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/xmtp2km.$MEXT
		   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
	  		echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/xmtp2km.$MEXT" |xargs gzip -f9
		
		   fi
	   fi
		

	   if [ -f mod/wanpipe_lip.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_lip.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanpipe_lip.$MEXT
		   if [ $GZ_MODULES ] && [ $GZ_MODULES=YES ]; then
	 		 echo "$ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanpipe_lip.$MEXT" |xargs gzip -f9
		   fi
	   fi


	   cat <<ENDOFTEXT > $CMP_INSTALL
#!/bin/bash

	   mv *.ko mod/ > /dev/null 2> /dev/null

 	   install -D -m 644 mod/sdladrv.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/sdladrv.$MEXT
	   install -D -m 644 mod/wanpipe.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe.$MEXT
	   install -D -m 644 mod/wanrouter.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanrouter.$MEXT
	   install -D -m 644 mod/af_wanpipe.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/af_wanpipe.$MEXT


	   if [ -f mod/wanpipe_syncppp.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_syncppp.$MEXT   $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_syncppp.$MEXT 
	   fi

	   if [ -f mod/wan_aften.$MEXT ]; then
	   install -D -m 644 mod/wan_aften.$MEXT   $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wan_aften.$MEXT 
	   fi

	   if [ -f mod/wanpipe_lip.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_lip.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanpipe_lip.$MEXT
	   fi

	   if [ -f mod/wanpipe_x25.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_x25.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_x25.$MEXT
	   fi
	   if [ -f mod/wanpipe_lapb.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_lapb.$MEXT $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_lapb.$MEXT
	   fi
	   if [ -f mod/wanpipe_dsp.$MEXT ]; then
	   install -D -m 644 mod/wanpipe_dsp.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe_dsp.$MEXT
	   fi

	   if [ -f mod/xmtp2km.$MEXT ]; then
	   install -D -m 644 mod/xmtp2km.$MEXT 	$ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/xmtp2km.$MEXT
	   fi

	   echo
	   echo "Modules installed in $ROOT/lib/modules/$KERNEL_VERSION: OK"
           echo

ENDOFTEXT

	   chmod 755 $CMP_INSTALL

	 cat <<ENDOFTEXT > .clean.$$
#!/bin/bash
	
rm -f *.ko
rm -f tmp/*.*o
rm -f mod/*.*o

echo "Clean Done"

ENDOFTEXT

	   cat .clean.$$ ../samples/clean.sh > $CMP_CLEAN

	   chmod 755 $CMP_CLEAN
	   
	else
	   install -D -m 644 mod/sdladrv.o $ROOT/lib/modules/$KERNEL_VERSION/net/sdladrv.o
	   install -D -m 644 mod/wanpipe.o $ROOT/lib/modules/$KERNEL_VERSION/net/wanpipe.o
	   install -D -m 644 mod/wanrouter.o $ROOT/lib/modules/$KERNEL_VERSION/misc/wanrouter.o
	   install -D -m 644 mod/af_wanpipe.o $ROOT/lib/modules/$KERNEL_VERSION/misc/af_wanpipe.o
	   if [ -f mod/wanpipe_syncppp.o ]; then
	   install -D -m 644 mod/wanpipe_syncppp.o   $ROOT/lib/modules/$KERNEL_VERSION/net/wanpipe_syncppp.o
	   fi

	   if [ -f mod/wan_aften.o ]; then
	   install -D -m 644 mod/wan_aften.o   $ROOT/lib/modules/$KERNEL_VERSION/misc/wan_aften.o
	   fi
	
	   if [ -f mod/wanpipe_lip.o ]; then
	   install -D -m 644 mod/wanpipe_lip.o 	$ROOT/lib/modules/$KERNEL_VERSION/misc/wanpipe_lip.o
	   fi

	fi

	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		return 1
	fi

# End of !LITE
	fi

	if test -z $ROOT; then
		#Check dependencies.
		eval "depmod -a 2> $PROD_HOME/tmp.$$"
		if [ -f $PROD_HOME/tmp.$$ ]; then
			eval "grep wanpipe -i $PROD_HOME/tmp.$$ 2> /dev/null" 
			rc1=$?
			eval "grep sdladrv -i $PROD_HOME/tmp.$$ 2> /dev/null"
			rc2=$?
			eval "grep wanrouter -i $PROD_HOME/tmp.$$ 2> /dev/null"
			rc3=$?
			eval "grep af_wanpipe -i $PROD_HOME/tmp.$$ 2> /dev/null"
			rc4=$?

			if [ $rc1 -eq 0 ] || [ $rc2 -eq 0 ] || [ $rc3 -eq 0 ] || [ $rc4 -eq 0 ]; then
				echo "WARNING: Module dependencies failed!"
				echo ""
				echo "       The MODULE_VERSIONS in the current linux source"
				echo "       are different from the current linux image."
				echo "       Or the MODULE_VERSIONS have been turned off in"
				echo "       the current linux source."
				echo
				echo "       In this case, take this messages as a WARNING, and"
				echo "       proceed with ${DISTR_NAME} installation." 
				echo "       After the installation is complete, run"
				echo 
				echo "          wanrouter hwprobe"
				echo
				echo "       to test ${DISTR_NAME} kernel modules!."
				echo "       If the hardware probe is successfull ignore the"
				echo "       above message, otherwise call Sangoma Tech Support"
				echo ""
				rm -f $PROD_HOME/tmp.$$
				if [ -d "$DRIVER_TMP_DIR" ]; then
					rm -rf $DRIVER_TMP_DIR 
				fi
				pause
			fi
			rm -f $PROD_HOME/tmp.$$
		fi
	fi

        #OPTIONAL
	if [ -d "$DRIVER_TMP_DIR" ] && [ "$DEVEL_DEBUG" = "NO" ]; then
		rm -rf $DRIVER_TMP_DIR 
	fi

	getyn "Visually Confirm that driver compilation was successful!"
	if [ $? -eq 0 ]; then
		echo "Compilation Successful."
		DRIVERS_COMPILED=yes
	else
		echo "Compilation Failed!"
		return 1
	fi

	return 0
}

function install_ssmg_ss7()
{

	if [ $SSMG_SS7 != "YES" ]; then
		return 0
	fi

	if [ $NO_SMG_INSTALL -eq 1 ]; then
        return 0
	fi	
		
	banner
	
	check_sctp_utility
	find_ast_dirs
	
	eval "install_sangoma_mgd"
	if [ $? -ne 0 ]; then
		echo "-------------------------------------"
		echo "Error: SMG Libraries Failed to install"	
		echo "Please Contact Sangoma Support!"
		echo "-------------------------------------"
		exit 1;
	fi
	echo 

	cd $PROD_HOME/$SSMG_DIR
	cd sangoma_mgd.trunk 

	echo "Installing SMG Daemon..."	
	echo
	if [ -z $ROOT ]; then
		eval "./install -ss7 -pbxdir $AST_SOURCE_DIR"
	else
		eval "./install -ss7 -rootdir $ROOT -pbxdir $AST_SOURCE_DIR"
	fi
	if [ $? -ne 0 ]; then
		echo "-------------------------------------"
		echo "Error: SMG Failed to install"	
		echo "Please Contact Sangoma Support!"
		echo "-------------------------------------"
		exit 1;
	fi
	echo 
	
	install_smg_samples_ss7

	pause
}

function install_ssmg_pri()
{
	if [ $SSMG_PRI != "YES" ]; then
		return 0
	fi
	banner
	
	check_sctp_utility
	find_ast_dirs
	
	cd $PROD_HOME/$SSMG_DIR
	eval "./get_sangoma_prid.sh"
	if [ $? -ne 0 ]; then
		echo "Failed to obtain SMG PRI package"
		exit 1	
	fi
	cd sangoma_pri
	echo
	echo "Installing SMG PRI Daemon..."
	eval "make INSTALLPREFIX=$ROOT install > /dev/null "
	
	echo
	echo "----------------------------------------"
	echo "Sangoma PRI Installation Complete"
	echo
	echo " -> To configure for PRI run:"
	echo " -> /usr/bin/wancfg_smg"
	echo
	echo "----------------------------------------"
	echo
	pause
	
	eval "install_sangoma_mgd"
	if [ $? -ne 0 ]; then
		echo "-------------------------------------"
		echo "Error: SMG Libraries Failed to install"
		echo "Please Contact Sangoma Support!"
		echo "-------------------------------------"
		exit 1;
	fi
	echo
	
	cd $PROD_HOME/$SSMG_DIR
	cd sangoma_mgd.trunk
	
	echo "Installing SMG Daemon..."
	echo
	if [ -z $ROOT ]; then
		eval "./install -pri -pbxdir $AST_SOURCE_DIR"
	else
		eval "./install -pri -rootdir $ROOT -pbxdir $AST_SOURCE_DIR"
	fi
	if [ $? -ne 0 ]; then
		echo "-------------------------------------"
		echo "Error: SMG Failed to install"
		echo "Please Contact Sangoma Support!"
		echo "-------------------------------------"
		exit 1;
	fi
	echo
	

	install_smg_samples_bri
	pause
}


function install_ssmg_bri()
{

	if [ $SSMG_BRI != "YES" ]; then
		return 0
	fi
		
	banner
	
	check_sctp_utility
	find_ast_dirs

	cd $PROD_HOME/$SSMG_DIR
	cd sangoma_bri
	echo
	echo "Installing SMG BRI Daemon..."	
	eval "make INSTALLPREFIX=$ROOT install > /dev/null "

	echo
	echo "----------------------------------------"	
	echo "Sangoma BRI Installation Complete"
	echo
	echo " -> To configure for BRI run:"
	echo " -> /usr/bin/wancfg_smg"
	echo 
	echo "----------------------------------------"	
	echo
	
	pause	
	
	eval "install_sangoma_mgd"
	if [ $? -ne 0 ]; then
		echo "-------------------------------------"
		echo "Error: SMG Libraries Failed to install"	
		echo "Please Contact Sangoma Support!"
		echo "-------------------------------------"
		exit 1;
	fi
	echo 

	cd $PROD_HOME/$SSMG_DIR
	cd sangoma_mgd.trunk 

	echo "Installing SMG Daemon..."	
	echo
	
	if [ "$no_woomera_option" == "TRUE" ];then
		smg_installation_type="no_woomera"
	else
		smg_installation_type="bri"
	fi

	if [ -z $ROOT ]; then
		eval "./install -$smg_installation_type -pbxdir $AST_SOURCE_DIR"
	else
		eval "./install -$smg_installation_type -rootdir $ROOT -pbxdir $AST_SOURCE_DIR"
	fi

	if [ $? -ne 0 ]; then
		echo "-------------------------------------"
		echo "Error: SMG Failed to install"	
		echo "Please Contact Sangoma Support!"
		echo "-------------------------------------"
		exit 1;
	fi
	echo 

	install_smg_samples_bri
	pause
}


function install_sangoma_mgd ()
{
	if [ "$SSMG_INSTALLED" == "YES" ]; then
		return 0;
	fi
	
	cd $PROD_HOME/$SSMG_DIR
	
	banner

        cd $PROD_HOME/$SSMG_DIR
	cd sangoma_mgd.trunk

	if [ $superuser = "YES" ] && [ -z $ROOT ]; then
		eval "find /usr/local/lib -name 'libteletone*' > /dev/null 2>/dev/null"
		if [ $? -eq 0 ]; then 
			eval "find /usr/local/lib -name 'libteletone*' | xargs rm > /dev/null 2>/dev/null"		
		fi
	fi

	echo "Installing Sangoma Media Gateway Daemon..."
        cd lib/libteletone/
	eval "./configure --prefix=$ROOT/usr; make clean; make CC=$CC; make install " > /dev/null
        if [ $? -ne 0 ]; then
	  	echo "FAILED"
		return 1
	fi   
	if [ $superuser = "YES" ]; then
        	eval "ldconfig"
	fi

                
	SSMG_INSTALLED=YES
	return 0;	    
}


function install_smg_samples_bri()
{
	getyn "Append sample config in Asterisk Extensions and Iax Conf"
	if [ $? -ne 0 ]; then
          	return 0;
	fi
	cd $PROD_HOME/$SSMG_DIR
	cd sangoma_mgd.trunk 
	if [ -f $ROOT/etc/asterisk/extensions.conf ]; then
        	eval "grep -i outb-bri $ROOT/etc/asterisk/extensions.conf 2> /dev/null > /dev/null"
		if [ $? -ne 0 ]; then
          		cat $ROOT/etc/asterisk/extensions.conf ./conf_bri/woomera_ext.conf > conf.$$
	       	 	mv conf.$$ $ROOT/etc/asterisk/extensions.conf
			echo "Asterisk extensions.conf file updated with woomera config"
		else
			echo "Asterisk extensions.conf already updated"
			
		fi
	fi

	if [ -f $ROOT/etc/asterisk/iax.conf ]; then 
        	eval "grep -i outb-bri $ROOT/etc/asterisk/iax.conf 2> /dev/null > /dev/null"
		if [ $? -ne 0 ]; then
                	cat $ROOT/etc/asterisk/iax.conf ./conf_bri/woomera_iax.conf > conf.$$
			mv conf.$$ $ROOT/etc/asterisk/iax.conf 
			echo "Asterisk iax.conf file updated with bri guest config"
		else
                   	echo "Asterisk iax.conf already updated"       	
		fi
	fi

	return 0
}



function install_smg_samples_ss7()
{
	cd $PROD_HOME/$SSMG_DIR
	cd sangoma_mgd.trunk 
	getyn "Add Woomera config in Asterisk Extensions and Iax Conf"
	if [ $? -ne 0 ]; then
          	return 0;
	fi
	if [ -f $ROOT/etc/asterisk/extensions.conf ]; then
        	eval "grep -i outb-ss7 $ROOT/etc/asterisk/extensions.conf 2> /dev/null > /dev/null"
		if [ $? -ne 0 ]; then
          		cat $ROOT/etc/asterisk/extensions.conf ./conf_ss7/woomera_ext.conf > conf.$$
	       	 	mv conf.$$ $ROOT/etc/asterisk/extensions.conf
			echo "Asterisk extensions.conf file updated with woomera config"
		else
			echo "Asterisk extensions.conf already updated"
			
		fi
	fi

	if [ -f $ROOT/etc/asterisk/iax.conf ]; then 
        	eval "grep -i outb-ss7 $ROOT/etc/asterisk/iax.conf 2> /dev/null > /dev/null"
		if [ $? -ne 0 ]; then
                	cat $ROOT/etc/asterisk/iax.conf ./conf_ss7/woomera_iax.conf > conf.$$
			mv conf.$$ $ROOT/etc/asterisk/iax.conf 
			echo "Asterisk iax.conf file updated with ss7 guest config"
		else
                   	echo "Asterisk iax.conf already updated"       	
		fi
	fi

	pause

	return 0
}

function install_all ()
{
	echo "Installing ${DISTR_NAME} Files ... !"

	echo "Installing  ${DISTR_NAME} Utilities in $ROOT/usr/sbin"

	if [ ! -e $WAN_CONF_DIR ]; then
		\mkdir -p $WAN_CONF_DIR
		\mkdir -p $WAN_CONF_DIR/util
	fi

	cd $PROD_HOME/util
	make install WAN_VIRTUAL=$ROOT > /dev/null 2> /dev/null
	make install_wancfg WAN_VIRTUAL=$ROOT > /dev/null 2> /dev/null


	if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		cd $PROD_HOME
		\cp -rf samples $ROOT/etc/wanpipe
		install -D -m 755 $PROD_HOME/scripts/wanlite $ROOT/usr/sbin/wanlite
		pause
		return 0
	fi

	install -D -m 755 $WANROUTER_STARTUP_SMPL $ROOT/$WANROUTER_STARTUP

	cd $PROD_HOME/util/misc
	make install WAN_VIRTUAL=$ROOT > /dev/null 2> /dev/null

	echo "Installing wanrouter.rc in $ROOT/etc/wanpipe"
	cd $PROD_HOME
	install -D -m 644 wanrouter.rc $ROOT/etc/wanpipe/wanrouter.rc

	echo "Installing wanpipe libraries in $ROOT/etc/wanpipe"
	
	\mkdir -p $ROOT/etc/wanpipe/lib/
	\cp -f $PROD_HOME/util/wancfg_legacy/lib/* $ROOT/etc/wanpipe/lib/

	echo "Installing firmware in $ROOT/etc/wanpipe/firmware"
	\cp -rf firmware $ROOT/etc/wanpipe/

	if [ ! -f $ROOT/etc/wanpipe/interfaces ]; then
		\mkdir -p $ROOT/etc/wanpipe/interfaces
	fi

	echo "Installing documentation in $ROOT/usr/share/doc/wanpipe"
	if [ ! -d $ROOT/usr/share/doc/wanpipe ]; then
		\mkdir -p $ROOT/usr/share/doc/wanpipe
	fi
	\cp -f doc/* $ROOT/usr/share/doc/wanpipe
	\cp -f README* $ROOT/usr/share/doc/wanpipe

	echo "Installing sample api code in $ROOT/etc/wanpipe/api"
	\cp -rf api $ROOT/etc/wanpipe
	\cp -rf samples $ROOT/etc/wanpipe

	echo "Installing AFT Firmware update utility in $ROOT$WAN_CONF_DIR/util"	
	if [ ! -d $ROOT$WAN_CONF_DIR/util ]; then
		\mkdir -p $ROOT$WAN_CONF_DIR/util
	fi
	\cp -rf util/wan_aftup $ROOT$WAN_CONF_DIR/util/

	cd firmware
	if [ -e wan_aftup ]; then
		\rm -f wan_aftup 2> /dev/null
	fi
	\ln -s ../util/wan_aftup wan_aftup


	if [ ! -d $ROOT/etc/wanpipe/scripts ]; then
		\mkdir -p $ROOT/etc/wanpipe/scripts 
	fi

	echo "Installing driver headers in $ROOT/etc/wanpipe/api/include/linux"
	if [ ! -d $ROOT/etc/wanpipe/api/include/linux ]; then
		\mkdir -p $ROOT/etc/wanpipe/api/include/linux
	fi


	cd $PROD_HOME
	if [ -d wan_ec ]; then
		cp -rf wan_ec $ROOT/etc/wanpipe
		echo "Installing Hardware Echo Cancel Utilites"
		cd util/wanec_client
		make install WAN_VIRTUAL=$ROOT > /dev/null 2> /dev/null  
		cd $PROD_HOME
	else
		echo "Hardware Echo Cancel Utilites Not Installed"
	fi
	cd $PROD_HOME


	if [ ! -f $ROOT/etc/wanpipe/api/include/linux/ ]; then
		\mkdir -p $ROOT/etc/wanpipe/api/include/linux/
	fi

	\cp -f $DRIVER_UPDATE_DIR/include/*.* $ROOT/etc/wanpipe/api/include/linux/
	
	pause
	return 0
}

function uninstall_all ()
{
	echo "Uninstalling ${DISTR_NAME} Binaries!\n"

	cd $PROD_HOME/util
	make uninstall WAN_VIRTUAL=$ROOT > /dev/null 2> /dev/null

	if [ "$PKG_NAME" = "wanpipe-lite" ]; then
		pause
		return 0;
	fi

	cd $PROD_HOME/util/misc
	make uninstall WAN_VIRTUAL=$ROOT > /dev/null 2> /dev/null

	find /usr/lib -name 'libsangoma.*' | xargs rm -f
	find /usr/local/lib -name 'libsangoma.*' | xargs rm -f
	find /usr/lib -name 'libstelephony.*' | xargs rm -f
	find /usr/local/lib -name 'libstelephony.*' | xargs rm -f

	cd $PROD_HOME
	rm -f $ROOT/usr/sbin/wp_pppconfig
	rm -rf $ROOT/usr/doc/wanpipe
	rm -rf $ROOT/etc/wanpipe
	rm -rf $ROOT/usr/sbin/wanrouter

	pause
	return 0
}

function enable_custom_protocols ()
{
	local level=$1
	
	if test $NONINTERACTIVE; then
		return 0
	fi

	if [ "$level" != "" ]; then
		enable_protocols $DEFAULT_PROTOCOLS
	fi
	
	while [ 1 ];
	do

	banner

	if [ "$level" = "" ]; then
	cat <<ENDOFTEXT
DEFAULT Protocols
ENDOFTEXT

	if [ $FR_PROT = NO ]; then
echo -n "[FR]      : Frame Relay       "
	else
echo -n "[FR]*     : Frame Relay       "	
	fi
	if [ $PPP_PROT = NO ]; then
echo    "[PPP]     : PPP" 	
	else
echo    "[PPP]*    : PPP" 
	fi
	if [ $CHDLC_PROT = NO ]; then
echo -n "[CHDLC]   : Cisco HDLC        " 
	else
echo -n "[CHDLC]*  : Cisco HDLC        " 
	fi
	if [ $X25_PROT = NO ]; then
echo    "[X25]     : X25 API"
	else
echo    "[X25]*    : X25 API"
	fi

echo
#	cat <<ENDOFTEXT	
#	
#	Kernel Protocol Implementations
#ENDOFTEXT

	if [ $ADSL_PROT = NO ]; then
echo -n "[ADSL]    : ADSL (S518)       "
	else
echo -n "[ADSL]*   : ADSL (S518)       "
	fi
	if [ $ATM_PROT = NO ]; then
echo    "[ATM]     : ATM"
	else
echo    "[ATM]*    : ATM"
	fi
	if [ $MPPP_PROT = NO ]; then
echo    "[MPROT]   : MP Prot"
	else
echo    "[MPROT]*  : MP Prot"
	fi
	echo

	if [ $AFT_TE1_PROT = NO ]; then
echo -n "[AFT_TE1] : AFT_TE1 (A101/2/4)"
	else
echo -n "[AFT_TE1]*: AFT_TE1 (A101/2/4)"
	fi
	if [ $AFT_TE3_PROT = NO ]; then
echo    "[AFT_TE3] : AFT_TE3 (A105)"
	else
echo    "[AFT_TE3]*: AFT_TE3 (A105)"
	fi
echo

	fi

	cat <<ENDOFTEXT
API Protocols
ENDOFTEXT

	if [ $SDLC_PROT = NO ]; then
echo -n "[SDLC]    : SDLC              "
	else
echo -n "[SDLC]*   : SDLC              "	
	fi
	if [ $BISYNC_PROT = NO ]; then
echo    "[BISYNC]  : MP Bisync"
	else
echo    "[BISYNC]* : MP Bisync"
	fi
	if [ $BSCSTRM_PROT = NO ]; then
echo -n "[BSCSTRM] : Bisync Stream     "
	else 
echo -n "[BSCSTRM]*: Bisync Stream     "
	fi
	if [ $BITSTRM_PROT = NO ]; then
echo    "[BITSTRM] : Bit Stream"
	else
echo    "[BITSTRM]*: Bit Stream"
	fi
	if [ $POS_PROT = NO ]; then
echo -n "[POS]     : POS (S509/S515)   "
	else
echo -n "[POS]*    : POS (S509/S515)   "
	fi
	if [ $EDU_PROT = NO ]; then
echo    "[EDU]     : Wan EduKit"
	else
echo    "[EDU]*    : Wan EduKit"
	fi
	if [ $SS7_PROT = NO ]; then
echo -n "[SS7]     : SS7 L2 (S514)     "
	else
echo -n "[SS7]*    : SS7 L2 (S514)     "
	fi
	if [ $ANNEXG_PROT = NO ]; then
echo    "[MPAPI]   : MP API"
	else
echo    "[MPAPI]*  : MP API"
	fi
	if [ $ADCCP_PROT = NO ]; then
echo -n "[ADCCP]   : ADCCP LAPB API    "
	else
echo -n "[ADCCP]*  : ADCCP LAPB API    "
	fi
	if [ $ASYHDLC_PROT = NO ]; then
echo    "[ASYHDLC] : Async HDLC API"
	else
echo    "[ASYHDLC]*: Async HDLC API"
	fi
	if [ $LIPAPI_PROT = NO ]; then
echo -n "[LIPAPI]  : LIP XDLC/LAPB     "
	else
echo -n "[LIPAPI]* : LIP XDLC/LAPB     "
	fi
	if [ $TDM_PROT = NO ]; then
echo    "[TDM]     : TDMV Asterisk"
	else
echo    "[TDM]*    : TDMV Asterisk $TDM_DCHAN"
	fi
	if [ $XMTP2_PROT = NO ]; then
echo    "[XMTP2]   : XMTP2 SS7         "
	else
echo    "[XMTP2]*  : XMTP2 SS7         "
	fi

	cat <<ENDOFTEXT

[DEF] : Enable All Default    [API] : Enable All API
[ALL] : Enable All Protocols  [NONE]: Disable ALL Protocols

[EXIT|Q|q]: Exit Protocol Selection

ENDOFTEXT

echo -n "Please select a protocol option in [<opt>]: "

	read response
	
	if [ "$response" = "EXIT" ]; then
		return 0;
	fi

	if [ "$response" = "Q" ]; then
		return 0;
	fi

	if [ "$response" = "q" ]; then
		return 0;
	fi
	
	echo "$response" | grep "DEF" > /dev/null	
	if [ $? -eq 0 ]; then
		enable_protocols $DEFAULT_PROTOCOLS
	fi	

	echo "$response" | grep "^API" > /dev/null		
	if [ $? -eq 0 ]; then
		enable_protocols $API_PROTOCOLS
	fi

	echo "$response" | grep "ALL" > /dev/null
	if [ $? -eq 0 ]; then
		enable_protocols $DEFAULT_PROTOCOLS
		enable_protocols $API_PROTOCOLS
	fi

	echo "$response" | grep "NONE" > /dev/null
	if [ $? -eq 0 ]; then
		init_all_protocols
	fi

	echo "$response" | grep "TDM" > /dev/null
	if [ $? -eq 0 ]; then
		enable_protocols $response
		enable_protocols AFT_TE1
	fi

	if [ $response != "DEF" ] &&
           [ $response != "API" ] &&
           [ $response != "ALL" ] &&
           [ $response != "NONE" ] &&	 
	   [ $response != "TDM" ]; then 

		enable_protocols $response
		if [ $? -ne 0 ]; then
			pause
		fi
	fi

	done
}

# set the proper directory for headers depending on
# zaptel/dahdi version
set_zaptel_source_dir()
{
	ZAPTEL_SUPPORT="YES";
	DAHDI_SUPPORT="NO";

	if [ -f $ZAPTEL_INSTALL_DIR/linux/include/dahdi/kernel.h ]; then
		ZAPTEL_INSTALL_DIR="$ZAPTEL_INSTALL_DIR/linux"
	fi

	#Check if this is Dahdi
	if [ -d $ZAPTEL_INSTALL_DIR/include/dahdi ]; then
		# when Dahdi present ZAPTEL_SOURCE_DIR is not really the source dir, but the headers dir
		# no harm done, no conflict, just a bit misleading variable name 
		ZAPTEL_SOURCE_DIR=$ZAPTEL_INSTALL_DIR/include
		ZAPTEL_SYM_DIR=$ZAPTEL_INSTALL_DIR/drivers/dahdi
		DAHDI_SUPPORT="YES"
		ZAPTEL_SUPPORT="NO"
	#Check if this is post Zaptel-1.4.9
	elif [ -d $ZAPTEL_INSTALL_DIR/kernel ]; then
		ZAPTEL_SOURCE_DIR=$ZAPTEL_INSTALL_DIR/kernel
		ZAPTEL_SYM_DIR=$ZAPTEL_INSTALL_DIR/kernel
	#Good ol' zaptel
	else
		ZAPTEL_SOURCE_DIR=$ZAPTEL_INSTALL_DIR
		ZAPTEL_SYM_DIR=$ZAPTEL_INSTALL_DIR
	fi
}

search_and_replace()
{
	local input_file_name=$1
	local output_file_name=$2
	local search_str="$3"
	local replace_str="$4"
	local tmp_file=output.tmp

	#echo "input_file_name:$input_file_name"
	#echo "output_file_name:$output_file_name"
	#echo "search_str:$search_str"
	#echo "replace_str:$replace_str"

	eval "grep '$search_str' $input_file_name > /dev/null 2> /dev/null"

	if [ $? -ne 0 ]; then
		echo "Did NOT find the seached str:$search_str"
		return 1
	else
		#echo "Found the seached str"
		eval "sed 's/'\"$search_str\"'/'\"$replace_str\"'/' $input_file_name > $tmp_file"
		mv $tmp_file $output_file_name
	fi

	return $?
}

function main_zap_header_present()
{
        if [ ! -f $ZAPTEL_SOURCE_DIR/zaptel.h ] && [ ! -f $ZAPTEL_SOURCE_DIR/dahdi/kernel.h ]; then
		return 0;
	fi
	return 1;
}

function tdmv_get_zaptel_path ()
{

        if [ $ZAPTEL_PATH_OP != "YES" ]; then
		find_zap_dirs
	fi

if [ 0 ]; then
        if [ $ZAPTEL_PATH_OP != "YES" ]; then
                echo
                echo -e "\nPlease specify absolute path to Zaptel source directory"
		echo -e "\n[default:$ZAPTEL_INSTALL_DIR]\n"
	       	echo -n "<specify path:> "
                if [ ! -d $ZAPTEL_INSTALL_DIR ]; then
                 	echo -e "Warning: $ZAPTEL_INSTALL_DIR does not exist\n"
		fi
                if test -z $NONINTERACTIVE; then
                        read response

                                [ $response ] && {
                                 ZAPTEL_INSTALL_DIR=$response
				 set_zaptel_source_dir
                        }
                fi
        fi

	main_zap_header_present	
	if [ $? -eq 0 ]; then
                echo "   Zaptel/Dahdi source not found in $ZAPTEL_SOURCE_DIR"
                ZAPTEL_SOURCE_DIR="/usr/src/zaptel"
		ZAPTEL_INSTALL_DIR=$ZAPTEL_SOURCE_DIR
                if test $NONINTERACTIVE; then
                        return 1
                else
                        getyn "   Press Y to specify another Zaptel/Dahdi source directory, N to exit"
                        if [ $? -ne 0 ]; then
                                exit 1;
                        fi
                        tdmv_get_zaptel_path
                fi
       fi
fi
	#zaptel.c renamed to zaptel-base.c in zaptel v1.2.13 and later
        if [ -e $ZAPTEL_SOURCE_DIR/zaptel-base.c ]; then
                ZAPTEL_C_FILE="zaptel-base.c";
        fi
        return 0;
}

# this function seems unused and does not seem to need to be updated for Dahdi
function tdmv_apply_zaptel_dchan_patch_old ()
{
	local rc
	ZAPTEL_PATCH_FILE=zaptel.patch


	if [ ! -e $PROD_HOME/zaptel ]; then
		echo "Error: Zaptel Patch Directory Not Found!"
		return 1;
	fi
	
	lhome=`pwd`

	cd $ZAPTEL_SOURCE_DIR

	
	if [ ! -e CVS ]; then
		ZAPTEL_PATCH_FILE=zaptel-1.0.9.patch	
	fi

	
	if [ ! -f $PROD_HOME/zaptel/$ZAPTEL_PATCH_FILE ];then
		echo "Error: Zaptel Patch File zaptel/$ZAPTEL_PATCH_FILE Not Found!"
		cd $lhome
		return 1;
	fi


	eval "grep \"DCHAN_TX\" $ZAPTEL_C_FILE > /dev/null 2> /dev/null"
	if [ $? -eq 0 ]; then

		eval "grep \"ZT_DCHAN_TX_V2\" $ZAPTEL_C_FILE > /dev/null 2> /dev/null"
		if [ $? -eq 0 ]; then
			echo "Zaptel DCHAN patch V.02 already installed"
			cd $lhome
			return 0
		else
			echo "ERROR: Old Zaptel DCHAN patch detected in $ZAPTEL_SOURCE_DIR"
			echo
			echo "       Please install a fresh version of Zaptel source and"
			echo "       run ./Setup again."
			echo 
			cd $lhome
			exit 1
		fi
	fi
	
	cp $PROD_HOME/zaptel/$ZAPTEL_PATCH_FILE zaptel.patch 

	eval "patch -p1 < zaptel.patch"
	rc=$?
	
	echo
	
	if [ $rc -ne 0 ]; then
		echo "Zaptel DCHAN Patch Failed"
		rc=1
	else
		eval "grep \"ZT_DCHAN_TX_V2\" $ZAPTEL_C_FILE > /dev/null 2> /dev/null"
		if [ $? -eq 0 ]; then
			echo "Zaptel Source Patched with DCHAN V.02 Successfully"
			rc=0
		else
			echo "Zaptel DCHAN V.02 Patch Failed"
			rc=1
		fi
	fi

	cd $lhome

	return $rc 
}

function tdmv_apply_zaptel_chunk_patch () {
	lhome=`pwd`
	TEMP=tmp
	cd $ZAPTEL_SOURCE_DIR
	echo "Applying Zaptel/Dahdi Chunk patch..."
	echo " "

	filetopatch="zaptel.h"	
	chunkname="ZT_CHUNKSIZE"
	dhname="Zaptel"
	isdahdi="no"
	if [ -f $ZAPTEL_SOURCE_DIR/dahdi/kernel.h ]; then
		filetopatch="$ZAPTEL_SOURCE_DIR/dahdi/kernel.h"
		chunkname="DAHDI_CHUNKSIZE"
		dhname="Dahdi"
		isdahdi="yes"
	fi

        #modify zaptel.h or kernel.h
        eval "cat $filetopatch | sed '/^#define $chunkname/c\#define $chunkname          $ZAP_CHUNK' >$TEMP 2>/dev/null"
        if [ $? -ne 0 ]; then
                echo "   Failed to substitute $chunkname string in $filetopatch"
                exit 1
        else
                eval "\mv -f $TEMP $filetopatch"
                if [ $? -ne 0 ]; then
                        echo "   Failed to overwrite existing $filetopatch"
                        exit 1
                else
                        echo "   $dhname patched for chunk size successfully"
                        zaptel_modified=1
                fi
        fi

        #remove wct4xxp module from Makefile
	if [ $isdahdi = "no" ]; then
		eval "cat Makefile |sed 's/wct1xxp wct4xxp wcte11xp/wct1xxp wcte11xp/g'>$TEMP 2>/dev/null "
		if [ $? -ne 0 ]; then
			echo "   Failed to remove wct4xxp from Makefile"
			exit 1
		else
			eval "\mv -f $TEMP Makefile"
			if [ $? -ne 0 ]; then
				echo "   Failed to overwrite existing Makefile"
				exit 1
			else
				echo "   wct4xxp module removed from Makefile successfully"
				zaptel_modified=1
			fi
		fi
	fi

	cd $ZAPTEL_INSTALL_DIR
	if [ $isdahdi = "no" ]; then
		eval "cat Makefile |sed 's/^SUBDIR_MODULES:=.*//g'>$TEMP 2>/dev/null "
		if [ $? -ne 0 ]; then
			echo "   Failed to remove wct4xxp from Makefile"
			exit 1
		else
			eval "\mv -f $TEMP Makefile"
			if [ $? -ne 0 ]; then
				echo "   Failed to overwrite existing Makefile"
				exit 1
			else
				echo "   wct4xxp module removed from Makefile successfully"
				zaptel_modified=1
			fi
		fi

		if [ -f Makefile.kernel26 ]; then
			eval "cat Makefile.kernel26 | sed 's/^obj-m.*+=.*wct4xx.*//g'>$TEMP 2>/dev/null "
			if [ $? -ne 0 ]; then
				 echo "   Failed to remove wct4xxp from Makefile.kernel26"
				 exit 1
			
			else
				eval "\mv -f $TEMP Makefile.kernel26"
				echo "   wct4xxp module removed from Makefile.kernel26 successfully"
				zaptel_modified=1			
			fi
		fi

	fi # end if $isdahdi = "no"

	if [ $isdahdi = "yes" ]; then
		cd drivers/dahdi
	fi
	# for zaptel-1.2.26 or later (including Dahdi)
	if [ -f Kbuild ]; then
		eval "cat Kbuild | sed 's/^obj-.*+=.*wct4xx.*//g'>$TEMP 2>/dev/null "
		if [ $? -ne 0 ]; then
			 echo "   Failed to remove wct4xxp from Kbuild"
			 exit 1
		else
			eval "\mv -f $TEMP Kbuild"
			echo "   wct4xxp module removed from Kbuild successfully"
			zaptel_modified=1
		fi

		eval "cat Kbuild | sed 's/^obj-.*+=.*wcb4xx.*//g'>$TEMP 2>/dev/null "
		if [ $? -ne 0 ]; then
			echo "   Failed to remove wcb4xxp from Kbuild"
			exit 1
	
		else
			eval "\mv -f $TEMP Kbuild"
			echo "   wcb4xxp module removed from Kbuild successfully"
			zaptel_modified=1
		fi

		eval "cat Kbuild | sed 's/^obj-.*+=.*wctdm24xxp.*//g'>$TEMP 2>/dev/null "
		if [ $? -ne 0 ]; then
			echo "   Failed to remove wctdm24xxp from Kbuild"
			exit 1
		
		else
			eval "\mv -f $TEMP Kbuild"
			echo "   wctdm24xxp module removed from Kbuild successfully"
			zaptel_modified=1
		fi

		eval "cat Kbuild | sed 's/^obj-.*+=.*wcte12xp.*//g'>$TEMP 2>/dev/null "
		if [ $? -ne 0 ]; then
			echo "   Failed to remove wcte12xp from Kbuild"
			exit 1

		else
			eval "\mv -f $TEMP Kbuild"
			echo "   wcte12xp module removed from Kbuild successfully"
			zaptel_modified=1
		fi

	fi

	cd $lhome
	return 0;
}

function tdmv_apply_oslec_patch ()
{
	lhome_tmp=`pwd`
	cd ..
	lhome=`pwd`
	TEMP=tmp
	cd $ZAPTEL_SOURCE_DIR
	echo "Applying Zaptel/Dahdi OSLEC echocanceler..."
	echo " "
	
	dhname="Zaptel"
	isdahdi="no"
	if [ -f $ZAPTEL_SOURCE_DIR/dahdi/kernel.h ]; then
		filetopatch="$ZAPTEL_SOURCE_DIR/dahdi/kernel.h"
		dhname="Dahdi"
		isdahdi="yes"
		
		cd ..
		eval "mkdir drivers/staging"
		eval "cp -rf $lhome/OSLEC/echo drivers/staging "
		sed -i "s|#obj-m += dahdi_echocan_oslec.o|obj-m += dahdi_echocan_oslec.o|" drivers/dahdi/Kbuild
		echo 'obj-m += echo.o' > drivers/staging/echo/Kbuild
		make
		make install
		cd $lhome_tmp
	
	fi
}


function tdmv_apply_zaptel_echo_debug_patch ()
{
	local rc

	if [ -f $ZAPTEL_SOURCE_DIR/dahdi/kernel.h ]; then
		echo "Error: Patching for echo debugging not supported for Dahdi yet"
		return 1;
	fi

	if [ ! -e $PROD_HOME/zaptel ]; then
		echo "Error: Zaptel Patch Directory Not Found!"
		return 1;
	fi
	
	if [ ! -f $PROD_HOME/zaptel/$ZAPTEL_C_ECHO_DEBUG_PATCH ]; then
		echo "Error: file $ZAPTEL_C_ECHO_DEBUG_PATCH Not Found!"
		return 1;
	fi

	if [ ! -f $PROD_HOME/zaptel/$ZAPTEL_H_ECHO_DEBUG_PATCH ]; then
		echo "Error: file $ZAPTEL_H_ECHO_DEBUG_PATCH Not Found!"
		return 1;
	fi

	#######################################################################################
	lhome=`pwd`
	cd $ZAPTEL_SOURCE_DIR

	#check if some version of the patch is already installed in $ZAPTEL_C_FILE
	eval "grep \"GET_ECHO_SPIKE_SAMPLE\" $ZAPTEL_C_FILE > /dev/null 2> /dev/null"
	if [ $? -eq 0 ]; then
		echo "Echo Debugging patch for Zaptel already installed in $ZAPTEL_C_FILE."
		echo "Consider using fresh (unpatched) Zaptel source."
		cd $lhome
		return 0
	fi

	#check if some version of the patch is already installed in zaptel.h
	eval "grep \"ECHO_SPIKE_SAMPLE_LEN\" zaptel.h > /dev/null 2> /dev/null"
	if [ $? -eq 0 ]; then
		echo "Echo Debugging patch for Zaptel already installed in zaptel.h."
		echo "Consider using fresh (unpatched) Zaptel source."
		cd $lhome
		return 0
	fi

	#######################################################################################
	cp $PROD_HOME/zaptel/$ZAPTEL_C_ECHO_DEBUG_PATCH .

	eval "patch $ZAPTEL_C_FILE $ZAPTEL_C_ECHO_DEBUG_PATCH > /dev/null 2> /dev/null"
	rc=$?
	if [ $rc -ne 0 ]; then
		echo "Echo Detection patch for Zaptel Failed (1)"
		cd $lhome
		return 1
	fi

	#######################################################################################
	eval "search_and_replace zaptel.h zaptel.h \"$ZAPTEL_H_SEARCH_STR\" \"$ZAPTEL_H_ECHO_DEBUG_PATCH_STR\""
	rc=$?
	if [ $rc -ne 0 ]; then
		echo "Echo Detection patch for Zaptel Failed (2)"
		cd $lhome
		return 1
	fi

	#######################################################################################
	cp $PROD_HOME/zaptel/$ZAPTEL_H_ECHO_DEBUG_PATCH .
	eval "patch zaptel.h $ZAPTEL_H_ECHO_DEBUG_PATCH > /dev/null 2> /dev/null"
	rc=$?
	echo
	if [ $rc -ne 0 ]; then
		echo "Echo Detection patch for Zaptel Failed (3)"
		cd $lhome
		return 1
	fi
	#######################################################################################
	echo "   Zaptel Source patched with Echo Debugging code Successfully"
	zaptel_modified=1
	rc=0
	cd $lhome
	return $rc
}

function tdmv_apply_zaptel_edac_patch ()
{
	local rc

	if [ -f $ZAPTEL_SOURCE_DIR/dahdi/kernel.h ]; then
		echo "Error: TDMV Echo Detection and Control not supported for Dahdi yet"
		return 1;
	fi

	if [ ! -e $PROD_HOME/edac ]; then
		echo "Error: Zaptel Patch Directory Not Found!"
		return 1;
	fi
	
	if [ ! -f $PROD_HOME/edac/$EDAC_ZAP_PATCH_FILE ]; then
		echo "Error: Echo Detection patch file for Zaptel edac/$EDAC_ZAP_PATCH_FILE Not Found!"
		return 1;
	fi

	lhome=`pwd`

	cd $ZAPTEL_SOURCE_DIR

	#check if some version of the patch is already installed
	eval "grep \"SANGOMA_GET_ED_STATE\" $ZAPTEL_C_FILE > /dev/null 2> /dev/null"
	if [ $? -eq 0 ]; then
		echo "Echo Detection patch for Zaptel already installed."
		echo "Consider using fresh (unpatched) Zaptel source."
		cd $lhome
		return 0
	fi
	
	cp $PROD_HOME/edac/$EDAC_ZAP_PATCH_FILE .

	#eval "patch -F 3 -c -d $ZAPTEL_SOURCE_DIR < $EDAC_ZAP_PATCH_FILE"
	eval "patch -p1 < $EDAC_ZAP_PATCH_FILE"
	rc=$?
	
	echo
	
	if [ $rc -ne 0 ]; then
		echo "Echo Detection patch for Zaptel Failed"
		rc=1
	else
		eval "grep \"SANGOMA_GET_ED_STATE\" $ZAPTEL_C_FILE > /dev/null 2> /dev/null"
		if [ $? -eq 0 ]; then
			echo "Zaptel Source patched with Echo Detection V1.00 Successfully"
			rc=0
		else
			echo "Echo Detection and Control patch for Zaptel failed!"
			rc=1
		fi
	fi

	cd $lhome
	zaptel_modified=1
	return $rc 
}

function tdmv_apply_asterisk_edac_patch ()
{
	local rc

	tdmv_get_asterisk_source_path
	if [ $? -ne 0 ]; then
		return 1;
	fi

	if [ ! -e $PROD_HOME/edac ]; then
		echo "Error: Zaptel Patch Directory Not Found!"
		return 1;
	fi
	
	if [ -d $ASTERISK_INSTALL_DIR/CVS ]; then
		#We are running Asterisk CVS use the CVS patch
		EDAC_ASTERISK_PATCH_FILE=$EDAC_ASTERISK_CVS_PATCH_FILE
	fi
	
	if [ ! -f $PROD_HOME/edac/$EDAC_ASTERISK_PATCH_FILE ]; then
		echo "Error: Echo Detection patch file for Asterisk edac/$EDAC_ASTERISK_PATCH_FILE Not Found!"
		return 1;
	fi

	lhome=`pwd`

	cd $ASTERISK_INSTALL_DIR/channels

	#check if some version of the patch is already installed
	eval "grep \"SANGOMA_SPIKE_SAMPLE_LEN\" chan_zap.c > /dev/null 2> /dev/null"
	if [ $? -eq 0 ]; then
		echo "Echo Detection patch for Asterisk already installed."
		echo "Consider using fresh (unpatched) Asterisk source."
		cd $lhome
		return 0
	fi
	
	cd $ASTERISK_INSTALL_DIR

	cp $PROD_HOME/edac/$EDAC_ASTERISK_PATCH_FILE .

	eval "patch -p1 < $EDAC_ASTERISK_PATCH_FILE"
	rc=$?
	
	echo
	
	if [ $rc -ne 0 ]; then
		echo "Echo Detection patch for Asterisk Failed"
		rc=1
	else
		cd $ASTERISK_INSTALL_DIR/channels
		eval "grep \"SANGOMA_SPIKE_SAMPLE_LEN\" chan_zap.c > /dev/null 2> /dev/null"
		if [ $? -eq 0 ]; then
			echo "Asterisk Source patched with Echo Detection V1.00 Successfully"
			rc=0
		else
			echo "Echo Detection and Control patch for Asterisk failed!"
			rc=1
		fi
	fi

	cd $lhome


	return $rc 
}
function tdmv_compile_zaptel()
{
        lhome=`pwd`

        cd $ZAPTEL_INSTALL_DIR
	echo
        echo -n "   Removing current Zaptel compilation(make clean)..."
	if [ -f configure ]; then
          	eval "./configure >> $PROD_HOME/zaptel_compilation_log 2>> $PROD_HOME/zaptel_compilation_log"
	fi
        eval "make clean >> $PROD_HOME/zaptel_compilation_log 2>> $PROD_HOME/zaptel_compilation_log"   
        if [ ! $? -eq 0 ]; then
                cat $PROD_HOME/zaptel_compilation_log
                echo
                echo "Error: Could not remove current Zaptel Compilation"
                echo "       See $PROD_HOME/zaptel_compilation_log for details"
                echo "       Contact Sangoma Tech Support"
                echo
                getyn "Would you like to continue?"
                if [ $? -ne 0 ]; then
                        exit 1
                fi
        else
                echo "OK"
		if [ -e menuselect/mxml ]; then
			cd menuselect/mxml			
		               eval "grep \" $ZAPTEL_MENUSELECT_SEARCH_STR\"  Makefile.in > /dev/null 2> /dev/null"
			       if [ $? -eq 0 ]; then
				     eval "search_and_replace Makefile.in Makefile.in \"$ZAPTEL_MENUSELECT_SEARCH_STR\" \"$ZAPTEL_MENUSELECT_REMOVE\""
                               fi 
			       if [ -e Makefile ]; then
                                    eval "grep \" $ZAPTEL_MENUSELECT_SEARCH_STR\"  Makefile > /dev/null 2> /dev/null"
			       	    if [ $? -eq 0 ]; then
				         eval "search_and_replace Makefile Makefile \"$ZAPTEL_MENUSELECT_SEARCH_STR\" \"$ZAPTEL_MENUSELECT_REMOVE\""
                                    fi
			       fi	
		fi
        fi

	cd $ZAPTEL_INSTALL_DIR
        echo -n "   Recompiling/reinstalling Zaptel(make install)..."
        eval "make >> $PROD_HOME/zaptel_compilation_log 2>> $PROD_HOME/zaptel_compilation_log"
        if [ ! $? -eq 0 ]; then
		echo
		echo 
		echo "-------------------------------------------"
                cat $PROD_HOME/zaptel_compilation_log
		echo "-------------------------------------------"
                echo
                echo "Error: Zaptel recompilation/reinstallation failed"
                echo "       See $PROD_HOME/zaptel_compilation_log for details"
                echo "       Contact Sangoma Tech Support"
                echo
                getyn "Would you like to continue?"
                if [ $? -ne 0 ]; then
                        exit 1
                fi
        else
		eval "make install >> $PROD_HOME/zaptel_compilation_log 2>> $PROD_HOME/zaptel_compilation_log"    
                echo "OK"
		echo 
        fi
        cd $lhome
}

function tdmv_check_zaptel_udev()
{
        echo -n "Checking for UDEV Zaptel compatibility..."
        if [ ! -e /etc/udev ]; then
		echo
                echo "   UDEV rules not used "
                return 0
        fi

	if [ $DAHDI_SUPPORT = "YES" ]; then
		echo "     Dahdi installed, no need to add UDEV rules"
		return 0
	fi


	#UDEV rules
        if [ ! -f /etc/udev/rules.d/50-udev.rules ]; then
                echo "   UDEV rules not found/or not used "
                return 0
        else
        	eval "grep \"zapctl\" /etc/udev/rules.d/50-udev.rules > /dev/null"
       		if [ $? -ne 0 ]; then
			echo 
			getyn "   Would you like to add UDEV rules for Zaptel devices ?"
        	        if [ $? -eq 0 ]; then
       				cp /etc/udev/rules.d/50-udev.rules /etc/udev/rules.d/50-udev.rules.old
        		#	echo "Your original udev rules have been copied to /etc/udev/rules.d/50-udev.rules.old"
        
				cat $PROD_HOME/samples/udevRulesPatch >> /etc/udev/rules.d/50-udev.rules
        			eval "grep \"zapctl\" /etc/udev/rules.d/50-udev.rules > /dev/null"
    				if [ $? -eq 0 ]; then
                			echo "   UDEV rules applied successfully"
       				else
               				echo "   UDEV rules patch failed"
               				return 1
       				fi
                	 fi
       		else 
			echo "OK" 
		fi
		 
	fi
        #UDEV permissions
	if [ ! -f /etc/udev/permissions.d/50-udev.permissions ]; then
                echo "  UDEV permissions not found/or not used "
                return 0
        else	
		eval "cat /etc/udev/permissions.d/50-udev.permissions |grep zap |grep root:root  > /dev/null"
       		if [ $? -ne 0 ]; then
			echo 
			getyn "   Would you like to add UDEV permissions for root user ?"
        	        if [ $? -eq 0 ]; then
				cp /etc/udev/permissions.d/50-udev.permissions /etc/udev/permissions.d/50-udev.permissions.old
        		#	echo "Your original udev permisions have been copied to /etc/udev/permissions.d/50-udev.permissions.old"
        			
        			echo -e "\n# zaptel devices -- for running asterisk as root" >> /etc/udev/permissions.d/50-udev.permissions
       				echo -e "zap/*:root:root:05700" >> /etc/udev/permissions.d/50-udev.permissions
        			
				eval "cat /etc/udev/permissions.d/50-udev.permissions |grep zap |grep root:root:05700  > /dev/null"
    				if [ $? -eq 0 ]; then
                			echo "   UDEV root permissions applied successfully"
       				else
               				echo "   UDEV permissions patch failed"
       				fi
			fi
		fi
		
		eval "cat /etc/udev/permissions.d/50-udev.permissions |grep zap |grep asterisk:asterisk  > /dev/null"
       		if [ $? -ne 0 ]; then
			echo
			getyn "   Would you like to add UDEV Permissions for non-root user?"
        		if [ $? -eq 0 ]; then
               			echo -e "\n# zaptel devices -- for running asterisk as a different user " >> /etc/udev/permissions.d/50-udev.permissions
               			echo -e "zap/*:asterisk:asterisk:660" >> /etc/udev/permissions.d/50-udev.permissions
				       	
				eval "cat /etc/udev/permissions.d/50-udev.permissions |grep zap |grep asterisk:asterisk:660  > /dev/null"
    				if [ $? -eq 0 ]; then
                			echo "   UDEV non-root permissions applied successfully"
       				else
               				echo "  UDEV permissions patch failed"
       				fi
      			fi
		fi
	fi
	echo
	pause
	echo
}

function find_zap_dirs_invalid ()
{
	echo
	echo "Invalid Response $response"
	echo
	clear
	find_zap_dirs "$1"
}

function is_valid_zap_dir()
{
	# one more !%*?@ change from Digium and we need an array here :-)
	if [ -f $1/zaptel.h ] || [ -f $1/kernel/zaptel.h ] || [ -f $1/include/dahdi/kernel.h ] || [ -f $1/linux/include/dahdi/kernel.h ]; then
		return 1;
	fi
	return 0;
}

function find_zap_dirs ()
{
	local cnt
	local dir
	local zapdir_manual=0
	local zapdirs=$1

	if [ $zaptel_auto_install = "YES" ]; then
		banner
	fi
	

	echo
	echo "Looking for zaptel/dahdi directory in /usr/src ..."	
	echo "-------------------------------------------"
	if [ "$zapdirs" = "" ]; then
		zapdirs=`find /usr/src -maxdepth 2 -name 'zaptel*' | xargs `
		 if [ -d "/usr/src/zaptel" ]; then
                        zapdirs="/usr/src/zaptel "$zapdirs
                 fi
		dahdidirs=`find /usr/src -maxdepth 2 -name 'dahdi*' | xargs `
		 if [ -d "/usr/src/dahdi" ]; then
                        zapdirs="/usr/src/dahdi $zapdirs"
		 fi
		zapdirs="$dahdidirs $zapdirs"
	fi

	unset zapdir_array;

	if [ -f  $PROD_HOME/zaptel/zaptel.path ]; then
		zapextradir=`cat $PROD_HOME/zaptel/zaptel.path`
	fi

	cnt=1
	for dir in $zapdirs
	do
		if [ ! -d $dir ]; then
			continue
		fi

		is_valid_zap_dir $dir
		if [ $? -eq 0 ]; then
			continue;
		fi
		
		if [ "$dir" = "/usr/src/zaptel" ] && [ $cnt -ne 1 ]; then
                        continue;
                fi

		
		zapdir_array[$cnt]=$dir;
		echo "$cnt : $dir "

		cnt=$((cnt+1))
	done
	
	if [ $cnt -eq 1 ]; then
		echo
		echo "No zaptel/dahdi dirs found in /usr/src "
		echo "Please use option \"m\" to enter zaptel/dahdi path"
		echo
	fi
	echo "------------------------------------------ "

	for dir in $zapextradir
	do
		if [ ! -d $dir ]; then
			continue
		fi

		is_valid_zap_dir $dir
		if [ $? -eq 0 ]; then
			continue;
		fi

		zapdir_array[$cnt]=$dir;
		echo "$cnt : $dir    (entered manually) "

		cnt=$((cnt+1))
	done


	echo "------------------------------------------ "
	echo "m : Enter zaptel path manually"
	echo
#	echo "d2: Download Latest 1.2"
#	echo "d4: Download Latest 1.4"
	echo "(ctrl-c to Exit)"
	echo -n "Please select working zaptel directory [1-$((cnt-1))][m]: "

	response=1

	if [ -z $NONINTERACTIVE ] || [ $zaptel_auto_install = "YES" ]; then
	read response
	fi

	if [ "$response" = "" ]; then
		find_zap_dirs_invalid "$zapdirs"
	elif [ $response = "m" ]; then
		echo
		echo  "Please enter zaptel dir: [Default: $ZAPTEL_DFLT_INSTALL_DIR]"
		echo -n "#> "
		read response
		
		if [ "$response" = "" ]; then
			ZAPTEL_INSTALL_DIR=$ZAPTEL_DFLT_INSTALL_DIR		
		else
			ZAPTEL_INSTALL_DIR=$response
		fi

		zapdir_manual=1
	
#	elif [ $response = "q" ]; then
#		find_zap_dir_quit=1
#		return 1;

	elif [ $response -gt 0 ] && [ $response -lt $cnt ]; then
		ZAPTEL_INSTALL_DIR=${zapdir_array[$response]}
	else
		find_zap_dirs_invalid "$zapdirs"
	fi	

	set_zaptel_source_dir
	main_zap_header_present
	if [ $? -eq 0 ]; then
		echo
		echo "Error: zaptel.h or dahdi/kernel.h not found in $ZAPTEL_SOURCE_DIR"
		echo
		echo
		zapdir_manual=0
		pause 1
		clear
		find_zap_dirs "$zapdirs"
	fi
	
	if [ $find_zap_dir_quit -eq 1 ] ; then
		ZAPTEL_INSTALL_DIR=$ZAPTEL_DFLT_INSTALL_DIR	
		return 1
	fi

	if [ $zapdir_manual -eq 1 ]; then
		eval "grep \"$ZAPTEL_INSTALL_DIR\" $PROD_HOME/zaptel/zaptel.path 2> /dev/null > /dev/null "
		if [ $? -ne 0 ]; then
			echo "$ZAPTEL_INSTALL_DIR" >> $PROD_HOME/zaptel/zaptel.path
		fi
	fi

	#echo "GO AUTOMATIC ZAPDIR= $ZAPTEL_SOURCE_DIR"

	ZAPTEL_PATH_OP="YES";

	#zaptel.c renamed to zaptel-base.c in zaptel v1.2.13 and later
        if [ -e $ZAPTEL_SOURCE_DIR/zaptel-base.c ]; then
                ZAPTEL_C_FILE="zaptel-base.c";
        fi

	return 0;
	
}

function find_ast_dirs_invalid ()
{
	echo
	echo "Invalid Response $response"
	echo
	clear
	find_ast_dirs "$1"
}



function find_ast_dirs ()
{
	local cnt
	local dir
	local astdir_manual=0
	local astdirs=$1
	local astdirs1


	if [ "$AST_PATH_OP" = "YES" ]; then
		return;
	fi

	echo
	echo "Looking for Asterisk/CallWeaver directory in /usr/src ..."	
	echo "-------------------------------------------"
	if [ "$astdirs" = "" ]; then
		astdirs=`find /usr/src -maxdepth 2 -name 'asterisk*' | xargs `
		if [ -d "/usr/src/asterisk" ]; then
			astdirs_tmp="/usr/src/asterisk "$astdirs
			astdirs=$astdirs_tmp
		fi
		 if [ -d "$AST_DFLT_INCLUDE_DIR" ]; then
            astdirs_tmp="$AST_DFLT_INCLUDE_DIR "$astdirs
			astdirs=$astdirs_tmp
		fi    

		astdirs1=`find /usr/src -maxdepth 2 -name 'callweaver*' | xargs `
		if [ -d "/usr/src/callweaver" ]; then
            astdirs1="/usr/src/callweaver "$astdirs1
        fi

		astdirs="$astdirs $astdirs1"
	fi

	unset astdir_array;

	if [ -f  $PROD_HOME/zaptel/ast.path ]; then
		astextradir=`cat $PROD_HOME/zaptel/ast.path`
	fi

	cnt=1
	for dir in $astdirs
	do
		if [ ! -d $dir ]; then
			continue
		fi

		if [ $dir != "$AST_DFLT_INCLUDE_DIR" ]; then
			if [ ! -f $dir/include/asterisk.h ] && [ ! -f $dir/include/callweaver.h ]; then
				continue;
			fi
		
			if [ "$dir" = "/usr/src/asterisk" ] && [ $cnt -gt 2 ]; then
			   	continue;
			fi

			if [ "$dir" = "/usr/src/callweaver" ] && [ $cnt -ne 1 ]; then
				continue;
			fi
		fi
		
		astdir_array[$cnt]=$dir;
		echo "$cnt : $dir "

		cnt=$((cnt+1))
	done
	
	if [ $cnt -eq 1 ]; then
		echo
		echo "No asterisk/callweaver dirs found in /usr/src "
		echo "Please use option \"m\" to enter asterisk/callweaver path"
		echo
	fi
	echo "------------------------------------------ "

	for dir in $astextradir
	do
		if [ ! -d $dir ]; then
			continue
		fi

		if [ ! -f $dir/include/asterisk.h ] && [ ! -f $dir/include/callweaver.h ]; then
			continue;
		fi

		astdir_array[$cnt]=$dir;
		echo "$cnt : $dir    (entered manually) "

		cnt=$((cnt+1))
	done


	echo "------------------------------------------ "
	echo "m : Enter Asterisk/CallWeaver path manually"
	echo
#	echo "d2: Download Latest 1.2"
#	echo "d4: Download Latest 1.4"
	echo "(ctrl-c to Exit)"
	echo -n "Please select working Asterisk/CallWeaver directory [1-$((cnt-1))][m]: "

	response=1

	if [ -z $NONINTERACTIVE ] || [ $bri_auto_install = "YES" ]; then
	read response
	fi

	if [ "$response" = "" ]; then
		find_ast_dirs_invalid "$astdirs"
	elif [ $response = "m" ]; then
		echo
		echo  "Please enter Asterisk/CallWeaver dir: [Default: $AST_DFLT_INSTALL_DIR]"
		echo -n "#> "
		read response
		
		if [ "$response" = "" ]; then
			AST_INSTALL_DIR=$AST_DFLT_INSTALL_DIR		
		else
			AST_INSTALL_DIR=$response
		fi

		astdir_manual=1
	
#	elif [ $response = "q" ]; then
#		find_ast_dir_quit=1
#		return 1;

	elif [ $response -gt 0 ] && [ $response -lt $cnt ]; then
		AST_INSTALL_DIR=${astdir_array[$response]}
	else
		find_ast_dirs_invalid "$astdirs"
	fi	

	AST_SOURCE_DIR=$AST_INSTALL_DIR
			
	if [ $AST_SOURCE_DIR != "$AST_DFLT_INCLUDE_DIR" ]; then	 
		if [ ! -f $AST_SOURCE_DIR/include/asterisk.h ] && [ ! -f $AST_SOURCE_DIR/include/callweaver.h ]; then
			echo
			echo "Error: asterisk.h/callweaver.h not found in $AST_SOURCE_DIR"
			echo
			echo
			astdir_manual=0
			pause 1
			clear
			find_ast_dirs "$astdirs"
		fi
	fi
	
	if [ $find_ast_dir_quit -eq 1 ] ; then
		AST_INSTALL_DIR=$AST_DFLT_INSTALL_DIR	
		return 1
	fi

	if [ $astdir_manual -eq 1 ]; then
		eval "grep \"$AST_INSTALL_DIR\" $PROD_HOME/zaptel/ast.path 2> /dev/null > /dev/null "
		if [ $? -ne 0 ]; then
			echo "$AST_INSTALL_DIR" >> $PROD_HOME/zaptel/ast.path
		fi
	fi


	AST_PATH_OP="YES";

	return 0;
	
}



function tdmv_get_asterisk_source_path ()
{
	echo 
	echo -e "\nPlease specify absolute path to Asterisk source directory"
	echo -e "\n\t(Press Enter for Default: $ASTERISK_INSTALL_DIR)\n"
	if test -z $NONINTERACTIVE; then
		read response

		[ $response ] && {
			ASTERISK_INSTALL_DIR=$response
		}
	fi

	if [ ! -f $ASTERISK_INSTALL_DIR/channels/chan_zap.c ]; then
			
			cat <<ENDOFTEXT
WARNING: The Asterisk Source directory has not been
         found in $ASTERISK_INSTALL_DIR!
	 EDAC installation failed.			
ENDOFTEXT
		pause
		return 1;
	fi

	return 0;
}

function enable_protocols ()
{
	local PROT_MATCH=NO
	local PROTOCOL=$1
	local ARG
		

	ARG=${2:-NO}

	if [ "$PROTOCOL" = "DEF" ]; then
		PROTOCOL=$DEFAULT_PROTOCOLS
	fi	
	if [ "$PROTOCOL" = "ALL" ]; then
		PROTOCOL="$DEFAULT_PROTOCOLS $API_PROTOCOLS"
	fi	
	
	echo "$PROTOCOL" | grep "BRI" > /dev/null
	if [ $? -eq 0 ]; then
		echo "Enabling the AFT BRI SMG Support"
		SSMG_BRI="YES"
		PROT_MATCH=YES
	fi
	
	echo "$PROTOCOL" | grep "PRI" > /dev/null
	if [ $? -eq 0 ]; then
		echo "Enabling the AFT PRI SMG Support"
		SSMG_PRI="YES"
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "SS7" > /dev/null
	if [ $? -eq 0 ]; then
		echo "Enabling the AFT SS7 SMG Support"
		SSMG_SS7="YES"
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "FR" > /dev/null	
	if [ $? -eq 0 ]; then
		if [ $FR_PROT != YES ]; then
		echo "Enabling the FR Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_FR "
		fi
		PROT_MATCH=YES	
		FR_PROT=YES
		LIP_PROT=YES
	fi
	
	echo "$PROTOCOL" | grep "CHDLC" > /dev/null	
	if [ $? -eq 0 ]; then
		if [ $CHDLC_PROT != YES ]; then
		echo "Enabling the CHDLC Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_CHDLC "
		fi
		PROT_MATCH=YES	
		CHDLC_PROT=YES
		LIP_PROT=YES
	fi
	
	echo "$PROTOCOL" | grep "PPP" > /dev/null	
	if [ $? -eq 0 ]; then
		if [ $PPP_PROT != YES ]; then
		echo "Enabling the PPP Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_PPP "
		fi
		PROT_MATCH=YES
		PPP_PROT=YES	
		LIP_PROT=YES
	fi
	
      	echo "$PROTOCOL" | grep "X25" > /dev/null	
	if [ $? -eq 0 ]; then
		if [ $X25_PROT != YES ]; then
		echo "Enabling the X25 API Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_X25 "
		fi
		PROT_MATCH=YES	
		X25_PROT=YES
	fi

	echo "$PROTOCOL" | grep "ADSL" > /dev/null
	if [ $? -eq 0 ]; then
		
		if [ -z $ARCH ]; then
			ARCH=`uname -m`
		fi

		if [ $KERN_VER != 24 ] && [ $KERN_VER != 26 ] && [ $KERN_VER != 30 ]; then
			cat <<ENDOFTEXT
			
WARNING: The ADSL Protocol not supported on non 2.4.X kernels!
	 Please contact Sangoma Technologies for more info.
	 Tel.   905 474 1990 ex113
	 Email: techdesk@sangoma.com

ENDOFTEXT
			ADSL_PROT=NO
			PROT_MATCH=YES

		elif [ $ARCH = "x86_64" ] || [ $ARCH = "ia64" ]; then
			cat <<ENDOFTEXT
			
WARNING: The ADSL Protocol not supported on 64bit architectures!
	 Please contact Sangoma Technologies for more info.
	 Tel.   905 474 1990 ex113
	 Email: techdesk@sangoma.com

ENDOFTEXT
			ADSL_PROT=NO
			PROT_MATCH=YES

		else	
	
			if [ $ADSL_PROT != YES ]; then
			echo "Enabling the ADSL Protocol"
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_ADSL "
			fi
			ADSL_PROT=YES
			PROT_MATCH=YES
		fi
	fi

	echo "$PROTOCOL" | grep "KATM" > /dev/null 
	if [ $? -eq 0 ]; then

		if [ $KATM_PROT != YES ]; then
                	PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_LIP_KATM "  	
		fi      

		KATM_PROT=YES
		PROT_MATCH=YES  

		#Note that KATM will also match 
 		#ATM protocol, so ATM will automatically be
	        #enabled.
	fi


	echo "$PROTOCOL" | grep "ATM" > /dev/null
	if [ $? -eq 0 ]; then

		if [ $KERN_VER != 24 ] && [ $KERN_VER != 26 ] && [ $KERN_VER != 30 ]; then
			cat <<ENDOFTEXT
			
WARNING: The ATM Protocol not supported on kernels lower than 2.4.0!
	 Please contact Sangoma Technologies for more info.
	 Tel.   905 474 1990 ex113
	 Email: techdesk@sangoma.com

ENDOFTEXT
			ATM_PROT=NO
			PROT_MATCH=YES
		else	
	
			if [ $ATM_PROT != YES ]; then
			
				PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_LIP_ATM -DCONFIG_PRODUCT_WANPIPE_ATM "
			fi
			ATM_PROT=YES
			PROT_MATCH=YES
		fi
	fi

	
	echo "$PROTOCOL" | grep "XMTP2" > /dev/null	
	if [ $? -eq 0 ]; then
		if [ $XMTP2_PROT != YES ]; then
		echo "Enabling the SS7 XMTP2 Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_XMTP2 -DAFT_XMTP2_API_SUPPORT -I$DRIVER_UPDATE_DIR/src/xmtp2km "
		fi
		PROT_MATCH=YES	
		XMTP2_PROT=YES
		LIP_PROT=YES
	fi

	echo "$PROTOCOL" | grep "MFR" > /dev/null	
	if [ $? -eq 0 ]; then
		#Deprecated to be taken out
		PROT_MATCH=YES	
	fi

	echo "$PROTOCOL" | grep "MPROT" > /dev/null	
	if [ $? -eq 0 ]; then
		if [ $MPPP_PROT != YES ]; then
		echo "Enabling the Multi Protocol Driver"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_MULTPROT "
		fi
		PROT_MATCH=YES	
		MPPP_PROT=YES
	fi

	echo "$PROTOCOL" | grep "EDU" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $EDU_PROT != YES ]; then
		echo "Enabling the EDU Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_EDU "
		fi
		EDU_PROT=YES
		PROT_MATCH=YES
	fi
	
	echo "$PROTOCOL" | grep "BISYNC" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $BISYNC_PROT != YES ]; then
		echo "Enabling the BISYNC Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_BSC "
		fi
		BISYNC_PROT=YES
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "BITSTRM" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $BITSTRM_PROT != YES ]; then
		echo "Enabling the BITSTRM Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_BITSTRM "
		fi
		BITSTRM_PROT=YES
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "BSCSTRM" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $BSCSTRM_PROT != YES ]; then
		echo "Enabling the BSCSTRM Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_BSCSTRM "
		fi
		BSCSTRM_PROT=YES
		PROT_MATCH=YES
	fi


	echo "$PROTOCOL" | grep "SDLC" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $SDLC_PROT != YES ]; then
		echo "Enabling the SDLC Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_SDLC "
		fi
		SDLC_PROT=YES
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "POS" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $POS_PROT != YES ]; then
		echo "Enabling the POS Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_POS "
		fi
		POS_PROT=YES
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "ADCCP" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $ADCCP_PROT != YES ]; then
		echo "Enabling the ADCCP Lapb Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_ADCCP "
		fi
		ADCCP_PROT=YES
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "ASYHDLC" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $ASYHDLC_PROT != YES ]; then
		echo "Enabling the ASYHDLC API Protocol"
		PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_ASYHDLC "
		fi
		ASYHDLC_PROT=YES
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "AFT_TE1" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $AFT_TE1_PROT != YES ]; then
			echo "Enabling the AFT TE1 Support"
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_AFT -DCONFIG_PRODUCT_WANPIPE_AFT_CORE -DCONFIG_PRODUCT_WANPIPE_AFT_TE1 -DCONFIG_PRODUCT_WANPIPE_AFT_56K -DCONFIG_PRODUCT_WANPIPE_AFT_RM -DCONFIG_PRODUCT_WANPIPE_CODEC_SLINEAR_LAW  -DCONFIG_PRODUCT_WANPIPE_AFT_BRI  -DCONFIG_PRODUCT_WANPIPE_AFT_SERIAL -DCONFIG_PRODUCT_WANPIPE_AFT_A600 -DCONFIG_PRODUCT_WANPIPE_AFT_B601 -DCONFIG_PRODUCT_WANPIPE_AFT_B800  "
			if [ $REL != "3.4" ]; then
              	   PROTOCOL_DEFINES="$PROTOCOL_DEFINES  -DCONFIG_PRODUCT_WANPIPE_AFT_A700 "
			fi
		fi
		AFT_TE1_PROT=YES
		AFT_BRI_PROT=YES
		AFT_SERIAL_PROT=YES
		if [ $REL != "3.4" ]; then
			if [ $AFT_USB_PROT = "NO" ]; then
        		PROTOCOL_DEFINES="$PROTOCOL_DEFINES  -DCONFIG_PRODUCT_WANPIPE_USB "
				AFT_USB_PROT=YES
			else 
				echo "USB Support Disabled by user!"
			fi
		fi
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "AFT_TE3" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $AFT_TE3_PROT != YES ]; then
			echo "Enabling the AFT TE3 Support"
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_AFT_TE3 "
		fi
		AFT_TE3_PROT=YES
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "LIPAPI" > /dev/null
	if [ $? -eq 0 ]; then
		if [ $XDLC_PROT != YES ]; then
			echo "Enabling the XDLC Support"
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_XDLC "
		fi
		if [ $LAPB_PROT != YES ]; then
			echo "Enabling the LAPB Support"
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_LIP_LAPB -DCONFIG_PRODUCT_WANPIPE_LIP_LAPD "
		fi
		XDLC_PROT=YES
		LAPB_PROT=YES
		LIPAPI_PROT=YES
		PROT_MATCH=YES
		LIP_PROT=YES
	fi

	echo "$PROTOCOL" | grep "TDM" > /dev/null
	if [ $? -eq 0 ]; then
		tdmv_get_zaptel_path
                if [ $? -eq 0 ]; then
                        ZAP_MOD_DIR=/lib/modules/$(uname -r)
	
			if [ $KERN_VER -eq 24 ]; then
				ZAPTEL_NAME=zaptel.o
			else
				ZAPTEL_NAME=zaptel.ko
			fi

			zaplikeinstalls=0
			if [ -e $ZAP_MOD_DIR/zaptel/$ZAPTEL_NAME ]; then
				zaplikeinstalls=$((zaplikeinstalls+1))
			fi

			if [ -e $ZAP_MOD_DIR/misc/$ZAPTEL_NAME ]; then
				zaplikeinstalls=$((zaplikeinstalls+1))
			fi

			# Dahdi drops support for kernel 2.4, no need to check .o vs .ko
			if [ -e $ZAP_MOD_DIR/dahdi/dahdi.ko ]; then
				zaplikeinstalls=$((zaplikeinstalls+1))
			fi

			if [ $zaplikeinstalls -gt 1 ]; then
				echo 
				echo 
				echo 
				echo "-------------------------------------------------------------"
				echo "CRITICAL WARNING: Multiple ZAPTEL/DAHDI Installations Found"
				echo
				echo "./Setup has found MULTIPLE ZAPTEL/DAHDI driver installations"
				echo " in 2 or more of this locations:"
				echo "        $ZAP_MOD_DIR/zaptel and" 
				echo "        $ZAP_MOD_DIR/misc directory."
				echo "        $ZAP_MOD_DIR/dahdi directory."
				echo
				echo "  The ZAPTEL drivers in $ZAP_MOD_DIR/zaptel are OLD."
				echo
				echo "  This is illegal, and CAN cause Wanpipe to CRASH."
				echo
				echo "  Please solve this PROBLEM by removing OLD ZAPTEL"
				echo "  kernel modules before installing WANPIPE.  "
				echo
				echo "      eg: rm -rf $ZAP_MOD_DIR/zaptel"
				echo "          depmod -a"
				echo 
				echo "  For more info please Contact Sangoma Technologies."
				echo "-------------------------------------------------------------"
			
				TDM_PROT=NO
				TDM_DCHAN=
				echo

				exit 1
			else
				echo
		
				if [ $TDM_PROT != YES ]; then
					echo "Enabling the TDM Voice Asterisk Support"
					PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE "		
					ASTERISK_IFLAGS="-I$ZAPTEL_INSTALL_DIR"
					WANCFG_ZAPTEL_CFG=YES
				fi

				#Check for new zaptel hw hdlc option
				if [ -f $ZAPTEL_SOURCE_DIR/zaptel-base.c ]; then
					eval "grep hdlc_hard_xmit $ZAPTEL_SOURCE_DIR/zaptel-base.c > /dev/null 2> /dev/null"
					if [ $? -eq 0 ] ; then
						echo "                                                      "
						echo "Zaptel HW HDLC Support Detected: Enabling DCHAN Feature"
						echo "Native Zaptel HW HDLC Support Detected - No patch required"
                                                echo "Zaptel source unmodified"
						echo "                        "

						TDM_DCHAN="(DCHAN)"
						PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE_DCHAN  -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE_DCHAN_ZAPTEL "
					fi
 				fi

				# if this is Dahdi, no need to check, already include hdlc_hard_xmit
				if [ -f $ZAPTEL_SOURCE_DIR/dahdi/kernel.h ]; then
					echo "                                                      "
					echo "Dahdi HW HDLC Support Detected: Enabling DCHAN Feature"
					echo "Native Dahdi HW HDLC Support Detected - No patch required"
					echo "Dahdi source unmodified"
					echo "                        "
					TDM_DCHAN="(DCHAN)"
					DAHDI_MAJOR=`cat $ZAPTEL_SOURCE_DIR/dahdi/version.h |  grep define | cut -d'"' -f2 | cut -d'.' -f1`
					DAHDI_MINOR=`cat $ZAPTEL_SOURCE_DIR/dahdi/version.h |  grep define | cut -d'"' -f2 | cut -d'.' -f2`
					PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE_DCHAN -DDAHDI_$DAHDI_MAJOR$DAHDI_MINOR -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE_DCHAN_ZAPTEL -DDAHDI_ISSUES"
				fi
	
				#Check if dchan patch is already enabled 
				if [ "$TDM_DCHAN" = "" ]; then
					eval "grep ZT_DCHAN_TX_V2 $ZAPTEL_SOURCE_DIR/* 2> /dev/null > /dev/null"
					if [ $? -eq 0 ]; then
						TDM_DCHAN="(DCHAN)"
						PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE_DCHAN"
						echo "Sangoma DCHAN Patch detected in zaptel"
						zaptel_modified=1
					fi
				fi

				#If DCHAN patch is not enabled give option to enable it
				if [ "$TDM_DCHAN" = "" ]; then
				echo 
				echo
				getyn "Enable TDMV DCHAN Native HDLC Support & Patch Zaptel (recommended) ?"
				if [ $? -eq 0 ]; then

					PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE_DCHAN"
					echo
					eval "$PROD_HOME/patches/sangoma-zaptel-patch.sh $ZAPTEL_SOURCE_DIR"
					result=$?
					if [ $result -eq 0 ]; then
						TDM_DCHAN="(DCHAN)"
						echo "   Zaptel DCHAN Patch successful"
						echo
						zaptel_modified=1
					elif [ $result -eq 1 ]; then
						TDM_DCHAN="(DCHAN)"
						zaptel_modified=1
						echo
					else
						echo "Zaptel Update Failed!"	
						echo
						echo "Your zaptel source is now corrupted"
						echo "Please untar new zaptel source in $ZAPTEL_INSTALL_DIR."
						echo
						echo "Please contact Sangoma support!"
						echo
						TDM_DCHAN=

						exit 1
					fi
				fi
			fi
                        if [ $ZAP_CHUNK_OP == "YES" ] ; then
                               tdmv_apply_zaptel_chunk_patch
                        fi

						if [ $OSLEC == "YES" ]; then
							tdmv_apply_oslec_patch
						fi


			####################################################################
			if [ $ENABLE_ECHO_DEBUG -eq 1 ]; then
			getyn "Compile Echo Debugging Support for Zaptel (not supported for Dahdi yet) ? "
			if [ $? -eq 0 ]; then
				tdmv_apply_zaptel_echo_debug_patch
				if [ $? -eq 0 ]; then
					zaptel_modified=1
				else
					ENABLE_ECHO_DEBUG=0
					echo
					echo "Echo Debug Patch Failed!! Your Zaptel source may be corrupted!!"
				fi
				getyn "   Confirm Echo Debugging Support for Zaptel Patching ?"
				echo
				if [ $? -eq 1 ]; then
					exit 1
				fi
			fi	
			fi
			####################################################################

			if [ $ENABLE_EDAC -gt 0 ]  && [ "$ECHO_MASTER_PROT" = "NO" ]; then
			echo 
			getyn "Compile TDMV Echo Detection and Control (EDAC) Support (No Dahdi support yet) (y/n)? "
			if [ $? -eq 0 ]; then
				echo
				tdmv_apply_zaptel_edac_patch
				if [ $? -eq 0 ]; then
					echo
					echo "Note: Please recompile/reinstall ZAPTEL drivers" 
					echo
					echo
					getyn "Confirm EDAC Zaptel Patching: yes/no to continue!"
			
					#now patch Asterisk
					tdmv_apply_asterisk_edac_patch
					##############################
					if [ $? -eq 0 ]; then
						#both Zaptel and Asterisk patched successfully			
						zaptel_modified=1
						asterisk_modified=1
						getyn "Confirm EDAC Asterisk Patching: yes/no to continue!"
						ECHO_MASTER_PROT=YES
						PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_TDM_VOICE_ECHOMASTER"
					else
						echo
						ECHO_MASTER_PROT=NO
					fi
					##############################
				else
					echo
					ECHO_MASTER_PROT=NO
				fi
			fi	
			fi

				TDM_PROT=YES
				if [ $zaptel_modified ] && [ $zaptel_modified -eq 1 ] && [ "$ZAPTEL_COMPILE_DISABLE" = "NO" ]; then
					echo
					getyn "Recompile/reinstall Dahdi/Zaptel (recommended) ?"
					if [ $? -eq 0 ]; then
						tdmv_compile_zaptel
					else 
						echo "   Recompile/reinstall zaptel after Wanpipe installation"
					fi	
				fi
				if [ $asterisk_modified ] && [ $asterisk_modified -eq 1 ]; then
					getyn "Your Asterisk source was modified, recompile/reinstall zaptel ?"
					if [ $? -eq 0 ]; then
						echo "DavidY: Compile Asterisk here"
				#		tdmv_compile_asterisk
					else 
						echo "   Recompile/reinstall Asterisk after Wanpipe installation"
					fi	
				fi
				tdmv_check_zaptel_udev
			fi
		fi
		PROT_MATCH=YES
	fi

	echo "$PROTOCOL" | grep "MPAPI" > /dev/null
	if [ $? -eq 0 ]; then

		if [ ! -d $DRIVER_UPDATE_DIR/src/net/annexg ]; then

			if [ $ARG = YES ]; then
				ANNEXG_LOAD=YES;
			else
		
			cat <<ENDOFTEXT
WARNING: The MPAPI Protocol Stacks are not part of this release!
	 Please contact Sangoma Technologies
	 Tel.   905 474 1990 ex113
	 Email: techdesk@sangoma.com			
ENDOFTEXT
			pause
			
			fi
		else

			if [ $ANNEXG_PROT != YES ]; then
				echo "Enabling the MPAPI Protocol Stacks"
				PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_ANNEXG "
			fi
			ANNEXG_PROT=YES

			if [ $MPPP_PROT != YES ]; then
				echo "Enabling the Multi Protocol Driver"
				PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_MULTPROT "
			fi
			MPPP_PROT=YES
		fi
		PROT_MATCH=YES
	fi


	echo "$PROTOCOL" | grep "SS7" > /dev/null
	if [ $? -eq 0 ]; then
	
		if [ ! -f $DRIVER_UPDATE_DIR/src/net/sdla_ss7.c ]; then
			cat <<ENDOFTEXT
			
WARNING: The SS7 Protocol is not part of this release!
	 Please contact Sangoma Technologies
	 Tel.   905 474 1990 ex113
	 Email: techdesk@sangoma.com

ENDOFTEXT
			pause
		else

			if [ $SS7_PROT != YES ]; then
			echo "Enabling the SS7 Protocol"
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DCONFIG_PRODUCT_WANPIPE_SS7 "
			fi
			SS7_PROT=YES
		fi
		PROT_MATCH=YES
	fi

	
	if [ $PROT_MATCH = NO ]; then
		echo
		echo "Error: invalid --protocol option ($PROTOCOL)"
		echo
		echo "Available non-default protocols are: $AVAIL_PROTOCOLS";
		echo "Example:  ./Setup install --protocol=DEF"
		echo
		return 1
	fi

	return 0
}

function init_all_protocols ()
{
FR_PROT=NO
LIP_HDLC_PROT=NO
PPP_PROT=NO
CHDLC_PROT=NO
X25_PROT=NO
AFT_TE1_PROT=NO
AFT_BRI_PROT=NO
AFT_USB_PROT=NO
AFT_SERIAL_PROT=NO
AFT_TE3_PROT=NO
SSMG_SS7=NO
SSMG_PRI=NO
SSMG_BRI=NO
no_woomera_option="FALSE"
smg_installation_type="bri"

WAN_FRM_UPDATE_DRIVER=YES

LIP_PROT=NO
LIP_LOAD=NO

ECHO_MASTER_PROT=NO

ADSL_PROT=NO
ANNEXG_PROT=NO
ANNEXG_LOAD=NO
MPPP_PROT=NO
ATM_PROT=NO
KATM_PROT=NO
XMTP2_PROT=NO

SS7_PROT=NO
EDU_PROT=NO
BISYNC_PROT=NO
BITSTRM_PROT=NO
BSCSTRM_PROT=NO
SDLC_PROT=NO
POS_PROT=NO
ADCCP_PROT=NO
ASYHDLC_PROT=NO
TDM_PROT=NO

LAPB_PROT=NO
XDLC_PROT=NO
LIPAPI_PROT=NO
		
EXTRA_LINK_MODULES=""
PROTOCOL_DEFINES="-DCONFIG_PRODUCT_WANPIPE_BASE "

TDM_DCHAN=
}

function detect_rpm_build_utility()
{
	local use_rpmbuild=0

	RPM=`which rpmbuild`
	if [ "$RPM" = "" ]; then
		RPM=`which rpm`
		if [ "$RPM" = "" ]; then
			echo "Error: RPM executable not found!"
			exit 1;
		fi
	else
		use_rpmbuild=1
	fi

	rpmver=`$RPM --version 2> /dev/null | cut -d ' ' -f3 | cut -d '.' -f1`
	if [ ! -z $rpmver ] && [ $rpmver -lt 4 ]; then
		RPMOPT="--buildroot"
	else
		if [ $use_rpmbuild -eq 1 ]; then
			RPMOPT="--buildroot"
		else
			RPMOPT="--root"
		fi
	fi
}

function compile_aft_firmware_util()
{
        lhome=`pwd`

		\cp -rf $PROD_HOME/util/wan_aftup  $PROD_HOME/rpmbuild/etc/wanpipe/util/

        cd $PROD_HOME/rpmbuild/etc/wanpipe/util/wan_aftup
        echo "Compiling firmware update utilities..."
        eval "make wan_aftup" >/dev/null 2>/dev/null
        if [ ! $? -eq 0 ]; then
                echo "failed"
                exit
        else
                echo "done"
        fi


        \rm -f *.c
        \rm -f *.o
        \rm -f *.h
        \rm -f Makefile
        cd $lhome
}

function check_sctp_utility ()
{
	echo
	echo -n "Checking for SCTP Utilities...."
	if [ ! -e  /usr/include/netinet/sctp.h ] && [ ! -e /usr/include/sctp.h ]; then
		echo "Failed!"
		echo "Missing lksctp-tools-devel" >> $CMP_LOG
                echo "Error: lksctp-tools-devel package missing"
		echo "Install lksctp-tools-devel package (e.g yum install lksctp-tools-devel)"
		echo "  "
		exit 1;
		
	else 
		echo "OK."
	fi

}


function usage()
{
	if [ "$PKG_NAME" != "wanpipe-lite" ]; then
	cat <<ENDOFTEXT | less
USAGE:
======

./Setup {command}  
or
./Setup {command} [ optinal command extensions ] 
	
	commands:
	---------
	install  	: Install/Upgrade General Wanpipe
	dahdi		: Install Wanpipe for Dahdi
	zaptel		: Install Wanpipe for Zaptel
	xmtp2_api	: Install Wanpipe for MTP2 API mode

	remove   	: Uninstall WANPIPE
	remove_init     : Uninstall WANPIPE Boot Startup Scripts
	install_init    : Install WANPIPE Boot Startup Scripts

	drivers  	: Re-install and Re-compile
		   	      Wanpipe kernel device drivers only
	buildrpm 	: Build the custom WANPIPE RPM binary for the
	           	  current system.  
		   	      For further help read README.rpm
	helprpm  	: RPM build help information.
	builddeb	: Build the custom WANPIPE Debian binary 
		        : package for current system.
	utility  	: Re-compile WANPIPE Tools/Utilities
	<any key>	: Help

	optional command extensions:
	----------------------------

	--silent    	: Non interactive. Run all above commands
	            	  without user interaction.  Thus default
	            	  environment values are assumed such
	            	  as:
		      
	            	        Linux source dir:  $SOURCEDIR
	            	        Architecture    :  uname -m
	            	        Kernel Image    :  uname -r
		      
	--builddir  	: Install WANPIPE package into a virtual
	            	  directory. The path must be
	            	  absolute and must exist.  Default is set
	            	  to system root( / ).
	            	  eg: --builddir=/root/wanpipe_build
		      
	--with-linux	: Build modules using a custom linux
	            	  source directory.  Default value is
	            	  set to $SOURCEDIR
	            	  eg: --with-linux=/usr/src/linux-2.4.4

	--with-zaptel   : Build modules using a certain verion of
	            	  zaptel or dahdi
	            	  eg: --with-zaptel=/usr/src/zaptel-1.4.12
	            	      --with-zaptel=/usr/src/dahdi-linux-2.2.0.2
 
	--with-asterisk : Build modules using a certain verions of
	            	  Asterisk
	            	  eg: --with-asterisk=/usr/src/asterisk-1.6.0.9

	--arch	    	: Build modules using a custom defined 
	            	  architecture. (i686 or i586)
	            	  By default: (uname -m) 
	            	  eg: --arch=i686

	--split_rpms	: Option to split the rpm build into
	            	  util and modules package.  Thus, 
	            	  splitting user space utilities and
	            	  kernel modules into two packages.
	            	  Default: one rpm package containing
		    	               both utilites and modules.
	            	  eg: ./Setup buildrpm --split_rpms

	--linux-vanilla	: Compile wanpipe drivers as if the
	            	  current linux source is a vanilla source.
	            	  Used to remove the default assumption that
	            	  stock distribution  kernels pull changes 
	            	  from higher linux kernel versions. 			 

  	--no-gcc-debug	: Remove -g option out of gcc compile argumetns.

	--noautostart   : Do not install start scripts, used to overwrite
	            	  the install of these scripts when using --silent
 
	--64bit_4GB     : Use this option when installing on systems using
	            	  a 64bit kernel and 4GB of RAM or more.  Wanpipe
	            	  needs to be aware that 64bit memory mapping is
	            	  used.

	--dahdi-chunk   : Use to increase the chunk size of Dahdi.
	            	  Drastically improves performance in TDM Voice
	            	  See the wiki for more information

	--no_woomera	: Option to compile the driver without installing 
	            	  chan_woomera.

	--protocol		: Option to compile in extra protocols
	            	  that are not installed by default.
	            	  eg: ./Setup install --protocol=<PROT>
		      
		      Extra Protocols Supported:
		     
		      SS7    : SS7 Level 2 API prot support
		      
		      BITSTRM: BitStreaming Protocol support

		      BSCSTRM: Nasdaq BiSync API protocol

		      BISYNC : Multi-Point Bisync API protocol

		      SDLC   : SDLC API protocol support

		      EDU    : Wan EduKit Driver suporrt

		      POS    : POS (S509/S515) hw/prot support
		     
		      SDLC   : SDLC API protocol
		      
		      MPAPI  : Multi Protocol API: X25,LAPB,DSP
		      
		      ADCCP  : ADCCP API protocol (LapB)
		      
		      TDM    : Hardware TDM VOICE support to Asterisk PBX
		      
		      BRI    : Sangoma BRI + Media Gateway Support
		      

ENDOFTEXT

	else
		cat <<ENDOFTEXT

USAGE:
======

./Setup {command}  
	
	commands:
	---------
	install  : Install WANPIPE (LITE)
	remove   : Uninstall WANPIPE (LITE)
	<any key>: Help

ENDOFTEXT
	fi
	return 0
}

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


REL="3.5"
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin
KERNEL_VERSION=`uname -r`
KERNEL_UNAME=`uname -r`
PKG_NAME=wanpipe
DISTR_NAME="WANPIPE"
PROD=wanrouter
PROD_VER=7.0.34
PROD_HOME=`pwd`
META_CONF=$PROD_HOME/$PROD.rc
WAN_INTR_DIR=$PROD_HOME/interfaces
WAN_CONF_DIR=/etc/wanpipe
PROD_CONF=$PROD_HOME/wanpipe1.conf
PROD_PATCH=$PROD_HOME/patches
PROD_INIT=/usr/sbin/
FILELIST=$PROD_HOME/Filelist
SOURCEDIR=/lib/modules/$(uname -r)/build
DEBSRCDIR=/lib/modules/$(uname -r)/source
START_SCRIPT=S11$PROD
OLD_START=S05router
STOP_SCRIPT=K70$PROD
OLD_STOP=K10router
INCLUDE=$SOURCEDIR/include/linux
ROUTER_RC=$META_CONF
UTIL_DIR=$PROD_HOME/util
UTIL_BIN_DIR=$PROD_HOME/util/bin
FIX_211="Fix_below_2211.gz"
ARCH=`uname -m`
WAN_TOOLS="wanconfig sdladump wanpipemon wanpipemon_legacy wpkbdmon wpbackupd"
WANROUTER_STARTUP_SMPL=$PROD_HOME/samples/wanrouter
WANROUTER_STARTUP=/usr/sbin/wanrouter
LINUX_VANILLA=0
DISABLE_GCC_DEBUG=0
ENABLE_EDAC=0
ENABLE_ECHO_DEBUG=0
ZAPTEL_PATH_OP="NO"
ZAPTEL_COMPILE_DISABLE="NO"
BRI_MODULE_TEST="NO"
ZAP_CHUNK_OP="NO"
OSLEC="NO"
CMP_LOG=$PROD_HOME/setup_drv_compile.log
CMP_BUILD=build.sh
CMP_INSTALL=install.sh
CMP_CLEAN=clean.sh
DEVEL_DEBUG=NO
SSMG_DIR=ssmg
WANPIPE_INCLUDE_DIR=/usr/include/wanpipe
WANCFG_ZAPTEL_CFG=NO
WANCFG_ZAPTEL=/usr/sbin/wancfg_zaptel
WANCFG_DAHDI=/usr/sbin/wancfg_dahdi
WANCFG_SMG=/usr/sbin/wancfg_smg
find_zap_dir_quit=0
find_ast_dir_quit=0
zaptel_auto_install="NO"
dahdi_auto_install="NO"
bri_auto_install="NO"
pri_auto_install="NO"
setup_install_quick="NO"
MODSYM=Module.symvers
DEFAULT_KERNEL_VERSION="NO"
TDM_VOICE_ONLY=NO      #used to detect whether this is a zaptel/dahdi only install...no API compile then

echo > $CMP_LOG
echo "WANPIPE DRIVER COMPILE LOG" >> $CMP_LOG
echo "`date`" >> $CMP_LOG
echo "-----------------------------------" >> $CMP_LOG



DRIVERS_MOD_LIST="sdladrv.mod.c wanrouter.mod.c wanpipe_syncppp.mod.c wanpipe.mod.c af_wanpipe.mod.c"

DRIVERS_MPAPI_DSP="dsp_timer.c dsp_subr.c dsp_proc.c dsp_out.c dsp_in.c dsp_iface.c dsp_api_iface.c"
DRIVERS_MPAPI_LAPB="lapb_iface.c lapb_in.c lapb_out.c lapb_proc.c lapb_subr.c lapb_timer.c lapb_x25_iface.c"
DRIVERS_MPAPI_X25="x25_api_iface.c x25_dsp_iface.c x25_facils.c x25_iface.c x25_in.c x25_out.c x25_proc.c x25_subr.c x25_switch.c x25_timer.c x25_utils.c"


DRIVER_UPDATE_DIR=$PROD_PATCH/kdrivers
DRIVER_INC_DIR=$PROD_PATCH/kdrivers/include
DRIVER_TMP_DIR=$PROD_HOME/kdrvtmp
DRIVERS_COMPILED=no
NEW_IF_TYPE=NO

MAKE_PATCH_22X="makefile.patch.2.2.X"
MAKE_PATCH_240="makefile.patch.2.4.0"
MAKE_PATCH_244="makefile.patch.2.4.4"
MAKE_UTILS_PATCH_24X="makefile.patch.utils.2.4.X"
MAKE_UTILS_PATCH_22X="makefile.patch.utils.2.2.X"
AF_WANPIPE_MAKE_PATCH_24X="makefile.af_wanpipe.patch"

TEMP=$PROD_HOME/temp.$$
WANCFG=$PROD_HOME/util/wancfg_legacy/wancfg_legacy
CFGFT1=$PROD_HOME/util/ft1/wanpipe_cfgft1


RPMOPT="--root"
PROTOCOL=""
EXTRA_LINK_MODULES=""
PROTOCOL_DEFINES="-DCONFIG_PRODUCT_WANPIPE_BASE "
SS7_USER_ID="0"

ANNEXG_LOAD=NO
SCTP_LOAD=NO

ZAPTEL_DFLT_INSTALL_DIR="/usr/src/zaptel"
AST_DFLT_INCLUDE_DIR="/usr/include/asterisk"
AST_DFLT_INSTALL_DIR=$AST_DFLT_INCLUDE_DIR
AST_SOURCE_DIR=$AST_DFLT_INSTALL_DIR
AST_PATH_OP="NO"
ZAPTEL_SOURCE_DIR=$ZAPTEL_DFLT_INSTALL_DIR
ZAPTEL_INSTALL_DIR=$ZAPTEL_DFLT_INSTALL_DIR
ZAPTEL_C_FILE="zaptel.c"
ASTERISK_IFLAGS=
EDAC_ZAP_PATCH_FILE=ed_zaptel.patch
ZAPTEL_SUPPORT="NO"
DAHDI_SUPPORT="NO"

ASTERISK_INSTALL_DIR="/usr/src/asterisk"
EDAC_ASTERISK_PATCH_FILE=ed_asterisk.patch
EDAC_ASTERISK_CVS_PATCH_FILE=ed_asterisk_cvs.patch

########################################################################
# D channel "search and replace" version of patch
ZAPTEL_C_SEARCH_STR="chan->writen\[chan->inwritebuf\] = amnt;"
ZAPTEL_C_PATCH="if ((chan->flags \& ZT_FLAG_HDLC) \&\& chan->span->ioctl != NULL){\n\
				if (chan->span->ioctl(chan, ZT_DCHAN_TX_V2, amnt)==0){\n\
					return amnt;\n\
				}\n\
			}\n\
			chan->writen[chan->inwritebuf] = amnt;"
# D channel patching for zaptel version 1.2.17.1/1.4.2.1 or above
ZAPTEL_C_SEARCH_STR_NEW="chan->writen\[res\] = amnt;"
ZAPTEL_C_PATCH_NEW="if ((chan->flags \& ZT_FLAG_HDLC) \&\& chan->span->ioctl != NULL){\n\
                                if (chan->span->ioctl(chan, ZT_DCHAN_TX_V2, amnt)==0){\n\
                                        return amnt;\n\
                                }\n\
                        }\n\
                        chan->writen[res] = amnt;"
# Zaptel 1.4.2.1 "Menuselect" issue
ZAPTEL_MENUSELECT_SEARCH_STR="autoconf"
ZAPTEL_MENUSELECT_REMOVE=" "

#NOTE1: the 'sed' command does NOT work on more than one line, so the
#closing '*/' will be pushed AFTER the inserted strings.
ZAPTEL_H_SEARCH_STR=" \*  80-85 are reserved for dynamic span stuff"
ZAPTEL_H_PATCH=\
" \*  80-85 are reserved for dynamic span stuff\n\
 \*\/\n\
#define ZT_DCHAN_TX 	_IOR (ZT_CODE, 60, int)\n\
#define ZT_DCHAN_TX_V1  ZT_DCHAN_TX\n\
#define ZT_DCHAN_TX_V2  ZT_DCHAN_TX\n\/\*"
#NOTE2: the "/*" at the end needed to match the leftover '*/' after the comment
########################################################################
#Echo Debug patch is done in 2 parts: 	1. is search and replace
#					2. using 'patch' program
#The reason is: 'patch' alone fails, if DCHAN patch already applied
ZAPTEL_C_ECHO_DEBUG_PATCH=zaptel.c.echo_debug.patch
ZAPTEL_H_ECHO_DEBUG_PATCH=zaptel.h.echo_debug.patch

ZAPTEL_H_ECHO_DEBUG_PATCH_STR=\
" \*  80-85 are reserved for dynamic span stuff\n\
 \*\/\n\
#define GET_ECHO_SPIKE_SAMPLE 	_IOR (ZT_CODE, 64, int)\n\
#define SEND_ECHO_SPIKE		_IOR (ZT_CODE, 65, int)\n\/\*"

########################################################################
setup_cmd=$1;

# Detect distribution type (FULL or LITE)
DIR=${PROD_HOME##/*/}
if [ $DIR = "wanpipe_lite" ]; then
	PKG_NAME=wanpipe-lite
	DISTR_NAME="WANPIPE (LITE)"
	PROD_VER=`grep "WANPIPE_LITE_VERSION *\"" "${DRIVER_UPDATE_DIR}/include/wanpipe_version.h" | cut -d'"' -f2`
    	PROD_VER=`echo $PROD_VER | awk '{ gsub(" ", "") ; print }'`
    	if [ -z $PROD_VER ]; then
		PROD_VER=1.1.1
    	fi
	if [ "$setup_cmd" != "install" -a "$setup_cmd" != "remove" ]; then
		usage
		exit 1
	fi
fi

#Initialize supportd protocols
#that are not compiled by default
init_all_protocols 

#List of available non-standard protocols
#Used as part of an errror message
AVAIL_PROTOCOLS="
	SS7 EDU BISYNC BITSTRM BSCSTRM SDLC 
	POS EDU SDLC MPAPI ADCCP TDM
"

#Enable default protocols 
DEFAULT_PROTOCOLS="FR-CHDLC-PPP-MFR-MPROT-X25-AFT_TE1-AFT_TE3"
API_PROTOCOLS="SS7-BISYNC-BSCSTRM-BITSTRM-POS-EDU-SDLC-MPAPI-ADCCP-TDM-XDLC-ASYHDLC"

CC=gcc
USR_CC=
GCC_VER=3
GCC_CHECK="INIT"
KBUILD_VERBOSE=0
KBUILD_MODPOST_WARN=1
REGPARM_DISABLE=0
KBUILD_DISABLE=0
NO_AUTO_START=0
NO_SMG_INSTALL=0
PROTS=

ROOT=;

WITH_LINUX_OP="NO";
SPLIT_RPMS="NO";

check_bash
check_awk

#Check for kernel series 2.2.X or 2.4.X
eval "uname -r | grep \"^2.4.*\" > /dev/null"
if [ $? -eq 0 ]; then
	KERN_VER=24
	LINUXDRIVERS_NET="drivers/net/wan"
	DEFAULT_PROTOCOLS=$DEFAULT_PROTOCOLS"-ADSL-ATM"
else

	eval "uname -r | grep \"^2.6.*\" > /dev/null"
	if [ $? -eq 0 ]; then
		KERN_VER=26
		LINUXDRIVERS_NET="drivers/net/wan"
		DEFAULT_PROTOCOLS=$DEFAULT_PROTOCOLS"-ADSL-ATM"
	else
		eval "uname -r | grep \"^3.0.*\" > /dev/null"
		if [ $? -eq 0 ]; then
			KERN_VER=30
			LINUXDRIVERS_NET="drivers/net/wan"
			DEFAULT_PROTOCOLS=$DEFAULT_PROTOCOLS"-ADSL-ATM"
		else
			KERN_VER=22
			LINUXDRIVERS_NET="drivers/net"
		
			eval "uname -r | grep \"^2.0.*\" > /dev/null"
			if [ $? -eq 0 ]; then
				echo
				echo "Wanpipe drivers do not support 2.0.X kernels !!!"
				echo "Please upgrade to 2.2.X 2.4.X 2.6.X kernels"
				echo "or install an older version of wanpipe, version 2.2.2"
				echo
				exit 0;
			fi
		fi
	fi
fi
LINUXDRIVERS_WAN="net/wanrouter"

superuser=NO;
if [ "$UID" = 0 ]; then
	superuser=YES;
fi

# Check router home directory.
[ -d "$PROD_HOME" ] || {
	error "Router home directory ($PROD_HOME) not found"
	exit 1
}

NONINTERACTIVE=;

if [ "$setup_cmd" = "remove_init" ]; then 
	remove_init; 
	find /etc/rc* | grep wan
	exit; 
fi

if [ "$setup_cmd" = "install_init" ]; then 
	install_init; 
	find /etc/rc* | grep wan
	exit; 
fi


if [ "$setup_cmd" = "zaptel" ] || [ "$setup_cmd" = "dahdi" ] ; then
	zaptel_auto_install="YES"
	setup_install_quick="YES"
	if [ "$setup_cmd" = "dahdi" ]; then
		dahdi_auto_install="YES"
	fi
	setup_cmd="install"
	#EXTRA_ARGS=" --protocol=TDM --silent --no-zaptel-compile "
	#EXTRA_ARGS=" --protocol=TDM "
fi

if [ "$setup_cmd" = "xmtp2_api" ]; then
	setup_cmd="install"
	NO_SMG_INSTALL=1
	PROTS="AFT_TE1-XMTP2"
fi

if [ "$setup_cmd" = "bri" ]; then
	setup_cmd="install"
	zaptel_auto_install="YES"
	bri_auto_install="YES"
	SSMG_BRI=YES
fi

if [ "$setup_cmd" = "pri" ]; then
	setup_cmd="install"
	zaptel_auto_install="YES"
	pri_auto_install="YES"
	SSMG_PRI=YES
fi


if [ "$setup_cmd" = "buildrpm" ]; then
	EXTRA_ARGS=" --no-zaptel-compile "
fi

if [ "$PKG_NAME" != "wanpipe-lite" ]; then
         
	ARGS=$EXTRA_ARGS
	while [ ! -z "$2" ]; 
	do
        ARGS_tmp=$ARGS"$2 "
	ARGS=$ARGS_tmp
		shift
	done

	#echo "ARGS: $ARGS"

	for arg in $ARGS
	do
		#echo
		#echo "ARG VAL=$arg"
	
		case $arg in

		--silent*)
			if [ $bri_auto_install = "YES" ]; then
				#default	
				bri_auto_install="NO"
			elif [ $zaptel_auto_install = "YES" ]; then
				zaptel_auto_install="NO"
				PROTS=TDM;	
			fi
			zaptel_auto_install="NO"
			setup_install_quick="NO"
			bri_auto_install="NO"
			pri_auto_install="NO"
			NONINTERACTIVE=1;
			;;
		--linux-vanilla*)
			LINUX_VANILLA=1;
			;;
		--no-gcc-debug*)
			DISABLE_GCC_DEBUG=1;
			;;
			
		--usr-cc*)
			USR_CC=`echo $arg | cut -d'=' -f2`;
			eval "type $USR_CC";
			if [ $? -ne 0 ]; then
                		echo "Error C compiler: $USR_CC doesnt exist!"
				exit 1
			fi

			check_gcc
			if [ $? -ne 0 ]; then
				echo "Error: Failed to determine $USR_CC version";
              			exit 1
			fi
			CC=$USR_CC
			;;
		--kbuild-verbose*)
			KBUILD_VERBOSE=1
			;;

		--kbuild-modpost-warn*)
			KBUILD_MODPOST_WARN=1
			;;
			
		--regparm_disable*)
			REGPARM_DISABLE=1
			;;

		--devel-debug*)
			DEVEL_DEBUG="YES"
			;;
		--kbuild-disable*)
			KBUILD_DISABLE=1
			;;
		--edac*)
			#TAKEN OUT 
			;;
                --bri_module_test*)
                       BRI_MODULE_TEST="YES"
                       ;;
		--noautostart*)
			NO_AUTO_START=1
			;;
		
		--ignore-t1-yellow*)
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DWANPIPE_IGNORE_T1_YELLOW " 
			;;

		--64bit_4G*)
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DWANPIPE_64BIT_4G_DMA "
			;;

		--64bit_2G*)
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DWANPIPE_64BIT_2G_DMA "
			;;

		--hwec_noise_reduction*)
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DWANEC_ENABLE_NOISE_REDUCTION "
			;;

		--with-linux*)
			SOURCEDIR=`echo $arg | cut -d'=' -f2`;
			DEBSRCDIR=$SOURCEDIR
			if [ "$SOURCEDIR" = "" ]; then
				echo "Error invalied --with-linux option";
				exit 1;
			fi
			if [ ! -d "$SOURCEDIR" ]; then
				echo "Error: Linux source directory not found: $SOURCEDIR";
				exit 1;
			fi
			if [ ! -f "$SOURCEDIR/Makefile" ]; then
				echo "Error: No vaild linux source found in $SOURCEDIR";
				exit 1;
			fi
			INCLUDE=$SOURCEDIR/include/linux
			WITH_LINUX_OP="YES";
			;;

		--echo-debug*)
			ENABLE_ECHO_DEBUG=1;
			;;

		--zaptel-path*)
			ZAPTEL_INSTALL_DIR=`echo $arg | cut -d'=' -f2`;
			if [ "$ZAPTEL_INSTALL_DIR" = "" ]; then
				echo "Error invalid --zaptel-path option";
				exit 1;
			fi
			if [ ! -d "$ZAPTEL_INSTALL_DIR" ]; then
				echo "Error: Dahdi/Zaptel source directory not found: $ZAPTEL_INSTALL_DIR";
				exit 1;
			fi
			if [ ! -f "$ZAPTEL_INSTALL_DIR/Makefile" ]; then
				echo "Error: Invalid zaptel source found in $ZAPTEL_INSTALL_DIR";
				exit 1;
			fi
			ZAPTEL_PATH_OP="YES";
			echo "Dahdi/Zaptel path defined as: $ZAPTEL_INSTALL_DIR"

			set_zaptel_source_dir	
			
			;;

		--with-zaptel*)
			ZAPTEL_INSTALL_DIR=`echo $arg | cut -d'=' -f2`;
			if [ "$ZAPTEL_INSTALL_DIR" = "" ]; then
				echo "Error invalid --with-zaptel option";
				exit 1;
			fi
			if [ ! -d "$ZAPTEL_INSTALL_DIR" ]; then
				echo "Error: Dahdi/Zaptel source directory not found: $ZAPTEL_INSTALL_DIR";
				exit 1;
			fi
			if [ ! -f "$ZAPTEL_INSTALL_DIR/Makefile" ]; then
				echo "Error: Invalid zaptel source found in $ZAPTEL_INSTALL_DIR";
				exit 1;
			fi
			ZAPTEL_PATH_OP="YES";
			echo "Dahdi/Zaptel path defined as: $ZAPTEL_INSTALL_DIR"
			
			set_zaptel_source_dir			

			;;

		--with-asterisk*)
				AST_DFLT_INSTALL_DIR=`echo $arg | cut -d'=' -f2`;
				if [ "$AST_DFLT_INSTALL_DIR" = "" ]; then
					echo "Error invalid --with-asterisk option";
					exit 1;
				fi
				if [ ! -d "$AST_DFLT_INSTALL_DIR" ]; then
					echo "Error: Asterisk source directory not found: $AST_DFLT_INSTALL_DIR";
					exit 1;
				fi
				if [ $AST_DFLT_INSTALL_DIR != "$AST_DFLT_INCLUDE_DIR" ]; then
					if [ ! -f "$AST_DFLT_INSTALL_DIR/Makefile" ]; then
						echo "Error: Invalid Asterisk source found in $AST_DFLT_INSTALL_DIR";
						exit 1;
					fi
				fi
				AST_PATH_OP="YES";
				echo "Asterisk path defined as: $AST_DFLT_INSTALL_DIR"
				AST_SOURCE_DIR=$AST_DFLT_INSTALL_DIR
				;;
	
		 --no-zaptel-compile*)
                        ZAPTEL_COMPILE_DISABLE="YES";
                        ;;

		 --no-usb*)
		 		echo "USB Support Disabled"
		 	    AFT_USB_PROT="DISABLE"
				;;

		--builddir*)
			ROOT=`echo $arg | cut -d'=' -f2`;
			if [ "$ROOT" = "" ]; then
				echo "Error: invalid --builddir option";
				exit 1;
			fi
			tmp_val=`echo $ROOT | cut -d'/' -f1`
			if [ "$tmp_val" != "" ]; then
				echo "Error: invalid builddir directory: must be absolute path!";
				exit 1;
			fi
			if [ ! -d "$ROOT" ]; then
				echo "Error: builddir ($ROOT) not found: please create it first!";
				exit 1;
			fi
			export ASTBROOT=$ROOT;
			ASTBROOT=$ROOT;

			TMP_123=${WANPIPE_INCLUDE_DIR#/*}
			WANPIPE_INCLUDE_DIR=$ROOT/$TMP_123
			TMP_123=${WANCFG_ZAPTEL#/*} 
			WANCFG_ZAPTEL=$ROOT/$TMP_123
			TMP_123=${WANCFG_DAHDI#/*} 
			WANCFG_DAHDI=$ROOT/$TMP_123


			;;
		--acflags*)
			USER_CFLAGS=`echo $arg | cut -d'=' -f2`
			if [ "$USER_CFLAGS" = "" ]; then
				echo "Error: invalid --acflags option: [ string ]";
			fi
			;;

		--ocflags*)
			USE_CFLAGS=`echo $arg | cut -d'=' -f2`
			if [ "$USER_CFLAGS" = "" ]; then
				echo "Error: invalid --ocflags option: [ string ]";
			fi
			;;
	
		--protocol*)
			PROTS=`echo $arg | cut -d'=' -f2`;
			;;

		--ss7_user_id*)
			SS7_USER_ID=`echo $arg | cut -d'=' -f2`;
			if [ "$SS7_USER_ID" = "" ]; then
				echo "Error: invalid --ss7_user_id option: [ integer ]";
			fi
			;;

		--ss7_ioctl_api*)
			PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DSS7_IOCTL_INTERFACE "
			;;

		--arch*)
			ARCH=`echo $arg | cut -d'=' -f2`;

			if [ $ARCH != "i686" ] && [ $ARCH != "i586" ] && [ $ARCH != "i486" ] && [ $ARCH != "i386" ] && [ $ARCH != "x86_64" ];  then
				echo "Error: Invalid Architecture [i686|i586|i486|i386|x86_64]\n"
				exit 1;
			fi
			;;

        --wanpipe_dev_alloc_cnt*)
            WANPIPE_DEV_ALLOC_CNT="";
            WANPIPE_DEV_ALLOC_CNT=`echo $arg | cut -d'=' -f2`;

            echo "WANPIPE_DEV_ALLOC_CNT = $WANPIPE_DEV_ALLOC_CNT"
            rc=0;
            if [ "$WANPIPE_DEV_ALLOC_CNT" = "" ]; then
                rc=1;
            else
                if [ $WANPIPE_DEV_ALLOC_CNT -ge 1 ] && [ $WANPIPE_DEV_ALLOC_CNT -le 128 ]; then
                    rc=0;
                else
                    rc=1
                fi
            fi


            if [ $rc -eq 1 ]; then
                echo "Error: Invalid WANPIPE_DEV_ALLOC_CNT value: Must be number 1 to 128";
                exit 1;
            fi
            PROTOCOL_DEFINES="$PROTOCOL_DEFINES -DWANPIPE_DEVICE_ALLOC_CNT=$WANPIPE_DEV_ALLOC_CNT "
            ;;

		--split_rpms*)
			SPLIT_RPMS="YES";
			;;
		--force_smp)
			FORCE_SMP="YES";
			;;
		--gz-modules)
			GZ_MODULES="YES";
			;;

		--no_woomera)
			no_woomera_option="TRUE";
			;;
 			
		--zap-chunk* | --dahdi-chunk*)
            ZAP_CHUNK=`echo $arg | cut -d'=' -f2`;

             if [ $ZAP_CHUNK != "8" ] && [ $ZAP_CHUNK != "16" ] && [ $ZAP_CHUNK != "40" ] && [ $ZAP_CHUNK != "80" ];  then
                echo "Error: Invalid Dahdi/Zaptel Chunk size"
                exit 1;
            else
                echo "WARNING:"
                echo "The wct4xxp module will be removed from your system"
                getyn "Do you want to use custom Dahdi/Zaptel chunk size of $ZAP_CHUNK"
                if [ $? -eq 0 ]; then
                    ZAP_CHUNK_OP="YES"
                else
                    ZAP_CHUNK_OP="NO"
                fi
            fi
            ;;

        --with-oslec)
			echo "WARNING:"
			echo "You are going to use OSLEC as software echo canceler"
			echo "Note: If you want to use OSLEC, do not forget to turn off the hardware echo canceler in wanpipe configuration"
			getyn "Do you want to use OSLEC for Dahdi/Zaptel"
			if [ $? -eq 0 ]; then
				OSLEC="YES"
			else
				OSLEC="NO"
			fi
			;;
		*)
			echo "Invalid option $arg"
			exit 1;
			;;
		esac
	done

	if [ "$PROTS" != "" ]; then
		echo "$PROTS" | grep "DEF" > /dev/null
   		if [ $? -eq 0 ]; then
           	enable_protocols $DEFAULT_PROTOCOLS "YES"
   		fi

   		echo "$PROTS" | grep "^API" > /dev/null
   		if [ $? -eq 0 ]; then
           	enable_protocols $API_PROTOCOLS "YES"
   		fi

   		echo "$PROTS" | grep "ALL" > /dev/null
   		if [ $? -eq 0 ]; then
           	enable_protocols $DEFAULT_PROTOCOLS "YES"
   	 		enable_protocols $API_PROTOCOLS "YES"
   		fi

		echo "$PROTS" | grep "TDM" > /dev/null
   		if [ $? -eq 0 ]; then
           	enable_protocols AFT_TE1 "YES"
   		fi

		echo "$PROTS" | grep "BRI" > /dev/null
   		if [ $? -eq 0 ]; then
           	enable_protocols AFT_TE1 "YES"
           	enable_protocols BRI "YES"
   		fi

		echo "$PROTS" | grep "PRI" > /dev/null
   		if [ $? -eq 0 ]; then
           	enable_protocols AFT_TE1 "YES"
           	enable_protocols PRI "YES"
   		fi

		echo "$PROTS" | grep "SS7" > /dev/null
   		if [ $? -eq 0 ]; then
           	enable_protocols AFT_TE1 "YES"
			enable_protocols "XMTP2" "YES"
           	enable_protocols SS7 "YES"
   		fi

		enable_protocols "$PROTS" "YES"
		if [ $? -ne 0 ]; then
			exit 1
		fi
	fi

	if [ "$setup_cmd" = "drivers" ]; then
		apply_patches || exit 1
		compile_drivers || exit 1
		exit; 
	fi

	if [ "$setup_cmd" = "smgbri" ]; then
		SSMG_BRI=YES
		zaptel_auto_install="YES"
		bri_auto_install="YES"
		install_ssmg_bri;
		exit;
	fi

	if [ "$setup_cmd" = "smgpri" ]; then
		SSMG_PRI=YES
		zaptel_auto_install="YES"
		pri_auto_install="YES"
		install_ssmg_pri;
		exit;
	fi
	
	if [ "$setup_cmd" = "ssmg" ]; then
		install_sangoma_mgd; 
		exit; 
	fi

	if [ "$setup_cmd" = "utility" ]; then
		compile_src; 
		exit; 
	fi

	if [ "$setup_cmd" = "meta" ]; then
		install_config; 
		exit; 
	fi

	if [ "$setup_cmd" = "inst" ]; then
		install_all; 
		exit; 
	fi


	if [ "$setup_cmd" = "buildrpm" ] || [ "$setup_cmd" = "builddeb" ]; then

		if [ ! -d $SOURCEDIR ]; then
			echo
			echo "Error: Linux source dir $SOURCEDIR not found!"
			echo
			exit
		fi

		if [ "$setup_cmd" = "buildrpm" ]; then
			build_dir=rpmbuild
			package_name="RPM"
		else
			build_dir=debbuild
			package_name="DEB"
		fi


		if [ -d $PROD_HOME/$build_dir ]; then
			\rm -rf $PROD_HOME/$build_dir > /dev/null 2> /dev/null
		fi

		\mkdir -p $PROD_HOME/$build_dir	

		PROTS=${PROTS:-$DEFAULT_PROTOCOLS}

		enable_protocols $PROTS

		get_kernel_ver $SOURCEDIR

		banner

		echo "
		
	WANPIPE $package_name BUILD

Wanpipe $package_name will be build based on the 
following Environment variables.
	
	1. Linux Source Dir  : $SOURCEDIR

	2. Linux Source Name : $KERNEL_VERSION

	3. Current Image Name: $KERNEL_UNAME
	
	4. CPU Type          : $ARCH
	
	5. Wan Protocols     : $PROTS
	
	6. Build Directory   : $PROD_HOME/$build_dir 
"

    	if [ $TDM_PROT = "YES"  ]; then
            echo "	7. Dahdi/Zaptel Build Dir  : $ZAPTEL_INSTALL_DIR "
    	fi

    	echo
    	echo

    	if [ $KERNEL_UNAME != $KERNEL_VERSION ]; then
    		echo "
WARNING:

The items 2 and 3 should usually be identical! 

If they are not, you are building an $package_name for
a different kernel image name, Setup is assuming 
you know what you are doing :)

"
    	fi

    	getyn "Would you like to build WANPIPE $package_name ?"
    	if [ $? -ne 0 ]; then
    		exit 1
    	fi
		
		echo "$PROTS" | grep "TDM" > /dev/null
		if [ $? -eq 0 ]; then
		    $PROD_HOME/Setup install --silent --builddir=$PROD_HOME/$build_dir --with-linux=$SOURCEDIR --arch=$ARCH --protocol=$PROTS --ss7_user_id=$SS7_USER_ID --noautostart --no-zaptel-compile --zaptel-path=$ZAPTEL_INSTALL_DIR 
		else
		    $PROD_HOME/Setup install --silent --builddir=$PROD_HOME/$build_dir --with-linux=$SOURCEDIR --arch=$ARCH --protocol=$PROTS --ss7_user_id=$SS7_USER_ID --noautostart --no-zaptel-compile 
		fi

		if [ $? -ne 0 ]; then
			echo "Error: WANPIPE Installation Failed!"
			exit 1;
		fi

		if [ "$setup_cmd" = "buildrpm" ]; then
            compile_aft_firmware_util
			detect_rpm_build_utility

			if [ "$SPLIT_RPMS" = "YES" ]; then
				eval "$RPM -bb --define '_unpackaged_files_terminate_build 0' $RPMOPT $PROD_HOME/rpmbuild $PROD_HOME/rpmspec/wanpipe-util.rpmspec --target=$ARCH"
				eval "$RPM -bb --define '_unpackaged_files_terminate_build 0' --define 'kern_ver $KERNEL_VERSION' $RPMOPT $PROD_HOME/rpmbuild $PROD_HOME/rpmspec/wanpipe-mod.rpmspec --target=$ARCH"
			else
                eval "$RPM -bb --define 'kern_ver $KERNEL_VERSION' $RPMOPT $PROD_HOME/rpmbuild $PROD_HOME/rpmspec/wanpipe.rpmspec --target=$ARCH"
			fi

			if [ $? -eq 0 ]; then
				cat <<ENDOFTEXT

WANPIPE RPM BUILD SUCCESSFUL

The new rpm is located in /usr/src/redhat/RPMS/$ARCH
directory.

To install run:
	rpm -i --force <rpm name>


ENDOFTEXT
	
			else
				cat <<ENDOFTEXT

WANPIPE RPM BUILD FAILED

Possible Solutions:
-------------------

1. Please make sure that you have
   $SOURCEDIR directory pointing to a
   linux kernel source.

2. Page up the screen and try to find an
   error message during the build process.

3. Contact Sangoma Tech Support

ENDOFTEXT
			fi

		else
	
			\mkdir -p $PROD_HOME/$build_dir/DEBIAN/
			\cp -f deb_control/wanpipe.deb $PROD_HOME/$build_dir/DEBIAN/control
			\cp -f deb_control/postinst $PROD_HOME/$build_dir/DEBIAN/
			\cp -f deb_control/prerm $PROD_HOME/$build_dir/DEBIAN/

			dpkg -b $build_dir  > /dev/null 2> /dev/null
	
			if [ $? -eq 0 ]; then

				pver=${PROD_VER//\./}
				build_pkg_name="wanpipe_"$pver"-k"$KVER$KPATCH$KLVL$KEVER"_"$ARCH".deb"

				mv -f "$build_dir.deb" $build_pkg_name  
			
				cat <<ENDOFTEXT

WANPIPE DEB BUILD SUCCESSFUL

The new rpm is located in $PROD_HOME:  $build_pkg_name

To install run:
	dpkg -i <deb name>


ENDOFTEXT
			else
				cat <<ENDOFTEXT

WANPIPE DEB BUILD FAILED

Possible Solutions:
-------------------

1. Please make sure that you have
   $SOURCEDIR directory pointing to a
   linux kernel source.

2. Page up the screen and try to find an
   error message during the build process.

3. Contact Sangoma Tech Support

ENDOFTEXT

			fi
		fi

		if [ -d $PROD_HOME/$build_dir ]; then
			rm -rf $PROD_HOME/$build_dir > /dev/null 2> /dev/null
		fi
		exit 0;

	fi

	if [ "$1" = "helprpm" ]; then

		detect_rpm_build_utility

		cat <<ENDOFTEXT

Building a Custom RPM
---------------------

./Setup buildrpm  --with-linux=<absolute path> --arch=<custom architecture>

	Create a custom rpm using the kernel in
	--with-linux directory.  Default kernel
	location is $SOURCEDIR.

	1. The absolute path must point to a
	   configured (.config file must exist)
	   kernel source.  If path is not supplied
	   it's defaulted to $SOURCEDIR.

	2. The RPM will be build in a virtual
	   directory called $PROD_HOME/rpmbuild/. Thus, it
	   will not pollute current environment
	   except the patches added to the
	   linux source directory (defined above).

	3. --arch is used to specify architecutre option
	   during compilation of wanpipe kernel modules. 
	   Supported options: i686 to i386.
	   By default architecture is obtained using the 'uname -m'
	   command.

In order to further customise a WANPIPE
RPM the user can manully create one.

1) Install WANPIPE package into a virtual 
   directory (eg: $PROD_HOME/rpmbuild) 

   ./Setup install --silent --builddir=$PROD_HOME/rpmbuild

2) Customize the $PROD_HOME/rpmbulid directory.

   eg: Copy already created wanpipe1.conf 
       configuration file into 
       $PROD_HOME/rpmbuild/etc/wanpipe directory.
      
       So that the RPM installation will
       already have a configured wanpipe card.

3) Build the rpm based on the $PROD_HOME/rpmbuild
   directory:

   $RPM -bb $RPMOPT $PROD_HOME/rpmbuild \\ 
                                     $PROD_HOME/rpmspec/wanpipe.rpmspec

ENDOFTEXT
		exit 0;
	fi
fi


if [ "$setup_cmd" = "uninstall" ] || [ "$setup_cmd" = "remove" ]; then 
	remove; 
	uninstall_all
	exit; 
fi      


if [ "$setup_cmd" != "install" ] && [ "$setup_cmd" != "upgrade" ]; then
	usage
	exit 1
fi	

welcome || exit 0

if [ $zaptel_auto_install = "YES" ]; then
	NONINTERACTIVE=1
fi

prepare	|| exit 1
apply_patches || exit 1
compile_drivers  || exit 1

install_config || exit 1

compile_src || exit 1
install_all 

if [ $zaptel_auto_install != "YES" ]; then
install_init || exit 1
fi

install_ssmg_ss7
install_ssmg_bri
install_ssmg_pri

clean_up 
goodbye

if [ $zaptel_auto_install = "YES" ]; then
	NONINTERACTIVE=
fi

#NONINTERACTIVE=

if [ -z $NONINTERACTIVE ]; then
    if [ "$WANCFG_ZAPTEL_CFG" = "YES" ] && [ -e $WANCFG_ZAPTEL ]; then
    	echo 
    	if [ $SSMG_BRI == "YES" ]; then
    	echo "Wanpipe / Zaptel/Dahdi & SMG BRI Configuration"
    	echo "========================================"
    	else
    		if [ $DAHDI_SUPPORT = "YES" ]; then
    			echo "Wanpipe / Zaptel Configuration"
    		else
    			echo "Wanpipe / Dahdi Configuration"
    		fi
    	echo "=============================="
    	fi
    	echo
    	if  [ $SSMG_BRI == "YES" ]; then
    	echo "wancfg_smg configurator can create all wanpipe config files"
    	echo "for ZAPTEL as well as for SMG BRI."
    	else
    		if [ $DAHDI_SUPPORT = "YES" ]; then
    			echo "wancfg_zaptel configurator can create all wanpipe config files"
            		echo "for ZAPTEL including /etc/zaptel.conf file."
    			echo "Optionally: the configurator can also create Asterisk zapata.conf"
    		else
    			echo "wancfg_dahdi configurator can create all wanpipe config files"
            		echo "for DAHDI including /etc/dahdi/dahdi.conf file."
    			echo "Optionally: the configurator can also create Asterisk dahdi.conf"
    		fi
    	fi
    	echo "-----------------------------------------------------"
    	if [ $SSMG_BRI == "YES" ]; then
           	getyn "Would you like to configure wanpipe devices for ZAPTEL/DAHDI & BRI?"
    	else
    		if [ $DAHDI_SUPPORT = "YES" ]; then
           			getyn "Would you like to configure wanpipe devices for DAHDI?"
    		else
           			getyn "Would you like to configure wanpipe devices for ZAPTEL?"
    		fi
    	fi

       	if [ $? -eq 0 ]; then
    	    if [ $SSMG_BRI == "YES" ]; then
                eval "$WANCFG_SMG"
    	    else
    		    if [ $DAHDI_SUPPORT = "YES" ]; then
            	    eval "$WANCFG_DAHDI"
    		    else 
            	    eval "$WANCFG_ZAPTEL"
    		    fi
    	    fi
    	else
    		echo "Wanpipe Installation Complete"
    		echo "-----------------------------" 
    		if [ $SSMG_BRI == "YES" ]; then
    			echo "Please proceed to configure wanpipe user /usr/sbin/wancfg_smg"
    		else
    			if [ $DAHDI_SUPPORT = "YES" ]; then
    				echo "Please proceed to configure wanpipe user /usr/sbin/wancfg_dahdi"
    			else
    				echo "Please proceed to configure wanpipe user /usr/sbin/wancfg_zaptel"
    			fi
    		fi
    		echo
    	fi
    elif [ "$SSMG_BRI" = "YES" ]; then
    	echo 
    	echo "Wanpipe / SMG BRI Configuration"
    	echo "==============================="
    	echo
    	echo "wancfg_smg configurator can create all wanpipe devices"
            echo "for BRI as well as BRI config file and Asterisk config files."
    	echo "-----------------------------------------------------"
        getyn "Would you like to configure wanpipe devices for SMG BRI/Asterisk/CallWeaver?"

       	if [ $? -eq 0 ]; then
    		if [ $SSMG_BRI == "YES" ]; then
    	        	eval "$WANCFG_SMG"
    		else
    			if [ $DAHDI_SUPPORT = "YES" ]; then
    	        		eval "$WANCFG_DAHDI"
    			else 
    	        		eval "$WANCFG_ZAPTEL"
    			fi
    		fi
    	else
    		echo "Wanpipe Installation Complete"
    		echo "-----------------------------" 
    		echo "Please proceed to configure wanpipe user /usr/sbin/wancfg"
    		echo
    	fi
    fi
fi

