#!/bin/sh
# Setup		WANPIPE WAN Router Installation/Removal Script.
#
# Copyright	(c) 1996-2002, Sangoma Technologies Inc.
#
#		This program is free software; you can redistribute it and/or
#		modify it under the terms of the GNU General Public License
#		as published by the Free Software Foundation; either version
#		2 of the License, or (at your option) any later version.
# ----------------------------------------------------------------------------
# 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 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 ()
{
	eval "kgcc --version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		CC=kgcc
		return 0;
	fi
	
	eval "gcc --version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		CC=gcc
		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 "awk -W version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		AWK_SUPPORT=YES
	else
		AWK_SUPPORT=NO
	fi
}


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

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

	if test $NONINTERACTIVE; then
		return 0
	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()
{
	clearscr
	echo -e "\t----------------------------------------------------------"
	echo -e "\t          WAN Router v$PROD_VER Installation Script"
	echo -e "\t    Copyright (c) 1995-2002, Sangoma Technologies Inc."
	echo -e "\t----------------------------------------------------------"
	echo ""
	return 0
}

# ----------------------------------------------------------------------------
# Show welcome screen.
# ----------------------------------------------------------------------------
welcome()
{
	banner
	cat << ENDOFTEXT
WANPIPE INSTALLATION
	
You are about to install WANPIPE Multi-Protocol WAN Router into your system.  
This script will examine your system, then install, create and/or modify 
necessary files and directories.

You must have the full Linux source code in $SOURCEDIR directory
and development system (i.e. GNU C compiler and utilities) installed 
in order to be able to install this product.

The automatic WANPIPE kernel module compilation option will compile 
all necessary WANPIPE drivers; thus, no need to re-compile
the kernel.  Previously patched kernels can now be upgraded to the latest
WANPIPE release; thus, no need for a fresh kernel install.

Please read WanpipeInstallation.(pdf/txt) and the Release Notes before proceeding 
with the installation.

ENDOFTEXT
	getyn "Would you like to install WAN Router now?"
}

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

	if test "$DRIVERS_COMPILED" = yes; then

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

	1) Proceed to configure the WANPIPE drivers using the
	   /usr/sbin/wancfg GUI configurator. 
	2) Use the /usr/sbin/wanrouter startup scrip to start and stop
	   the router.
	3) Use /usr/sbin/cfgft1 to configure the (optional) onboard
	   CSU/DSU.
	4) The temporary wanpipe directory can now be deleted
	5) To uninstall WANPIPE package run ./Setup remove
		
Please read WanpipeInstallation.(pdf/txt) manual for further instructions.

IMPORTANT: 
---------
The Linux Kernel or Modules do NOT have to be manually 
recompiled.  WANPIPE kernel modules are already installed !!! 

ENDOFTEXT
	
		if test $ROOT; then

	cat <<ENDOFTEXT

WARNING: 
-------
	The newly compiled WANPIPE modules could not
	be checked for dependency errors due to the
	virtual installation directory $ROOT/.
	i.e. The depmod utility uses /lib/modules dir.
			       
	Try loading the modules manually from:
			       
	$ROOT/lib/modules/kernel/drivers/net/wan:
		insmod sdladrv
	$ROOT/lib/modules/kernel/net/wanrouter:
		insmod wanrouter
	$ROOT/lib/modules/kernel/drivers/net/wan:
		insmod syncppp
		insmod wanpipe
ENDOFTEXT

		fi
	
	else

	cat <<ENDOFTEXT
WANPIPE INSTALLATION: INCOMPLETE
	
WANPIPE utilities and configurators have been installed sucessfully.
However, WANPIPE kernel drivers still require compilation. Please 
proceed to the kernel and modules compilation to finish WANPIPE 
installation. Typically, this process includes the following steps:

	1) change your current directory to $SOURCEDIR
	2) configure kernel with 'make menuconfig'
	3) build new kernel (e.g.'make 'bzImage')
	4) build modules with 'make modules'
	5) install modules with 'make modules_install'
	6) updated /etc/lilo.conf and run lilo
	7) re-boot your system and load the new kernel !
	8) refer to the /usr/doc/wanpipe/WanpipeInstallation.(pdf/txt) for further
	   information on how to configure WANPIPE.
	9) The temporary wanpipe directory can now be deleted
       10) To uninstall WANPIPE package run ./Setup remove


Please read /usr/doc/WanpipeInstallation.(pdf/txt) 
manual for detailed instructions on how to configure and compile 
Linux kernel and WANPIPE modules. For more information about 
re-compiling the kernel refer to README file found in 
$SOURCEDIR directory.

ENDOFTEXT

	fi
}

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

	# Verify files and fix permissions.
	echo "Fixing file permissions..."
	fix_perms || {
		error "Product is not completely installed. Please re-install"
		return 1
	}


	echo -n "Checking for bash2 ... "

	if [ -f "/bin/bash2" ]; then
		echo "#!/bin/bash2" > tmp_file$$
		echo "OK"

		cat $WANCFG | awk '{ gsub("#!.*", "") ; print }' > $TEMP
		cat tmp_file$$ $TEMP > $WANCFG
		
		cat $CFGFT1 | awk '{ gsub("#!.*", "") ; print }' > $TEMP
		cat tmp_file$$ $TEMP > $CFGFT1

		cat $WANROUTER_STARTUP_SMPL | awk '{ gsub("#!.*", "") ; print }' > $TEMP
		cat tmp_file$$ $TEMP > $WANROUTER_STARTUP_SMPL

		rm -f tmp_file$$
		rm -f $TEMP
		
	else
		bash_ver=`echo $BASH_VERSION | cut -d'.' -f1 2> /dev/null`
		if [ $bash_ver -gt 1 ]; then

			echo "#!/bin/bash" > tmp_file$$
			echo "OK"

			cat $WANCFG | awk '{ gsub("#!.*", "") ; print }' > $TEMP
			cat tmp_file$$ $TEMP > $WANCFG
			
			cat $CFGFT1 | awk '{ gsub("#!.*", "") ; print }' > $TEMP
			cat tmp_file$$ $TEMP > $CFGFT1

			cat $WANROUTER_STARTUP_SMPL | awk '{ gsub("#!.*", "") ; print }' > $TEMP
			cat tmp_file$$ $TEMP > $WANROUTER_STARTUP_SMPL

			rm -f tmp_file$$
			rm -f $TEMP
			echo "OK"
		else
			echo "Failed!"
			echo -e "\n\tWarning: The wancfg and cfgft1 GUI configuration utilities"
			echo -e "\t         depend on Bash version 2 or greater." 
			echo -e "\t         (File /bin/bash2 not found, or /bin/bash is version 1.X)\n"
		fi
	fi

	rm -f tmp_file$$

	echo -n "Checking for ncurses library ... "
	
	if [ ! -f "/usr/include/ncurses.h" ] && [ ! -f "/usr/include/ncurses/ncurses.h" ]; then
		echo "Failed!"
		echo -e "\n\tWarning: The wancfg and cfgft1 GUI configuration utilties"
		echo -e "\t         require the ncurses libraries (eg: libncurses5-devel)."
		echo -e "\t         (File /usr/local/ncurses.h not found)\n"
	else
		echo "OK"
	fi


	echo -n "Checking for C developement tools ..."

	check_gcc 
	if [ $? -eq 0 ]; then
		echo "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

	echo -n "Checking for C++ developement tools ..."
	eval "g++ --version > /dev/null"
	if [ $? -eq 0 ]; then
		echo "OK"
	else
		echo "Failed!"
		echo -e "\n\tWarning: Wanpipe package requires development C++ tools to complete
		                      the installation.  Please install development package
				      before proceeding."
	fi
	
	echo -n "Checking for Perl developement tools ..."
	eval "perl --version > /dev/null"
	if [ $? -eq 0 ]; then
		echo "OK"
	else
		echo "Failed!"
		echo -e "\n\tWarning: Wanpipe package requires development Perl tools to complete
		                      the installation.  Please install development package
				      before proceeding."
	fi

	
	echo -n "Checking for AWK ..."
	eval "awk -W version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		echo "OK"
	else
		echo "Failed!"
		echo -e "\n\tWarning: Wanpipe 'wanrouter' startup script uses AWK.  Please
		                      install AWK before proceeding."
	fi

	echo -n "Checking for Patch ..."
	eval "patch --version 2> /dev/null > /dev/null"
	if [ $? -eq 0 ]; then
		echo "OK"
	else
		echo "Failed!"
		echo -e "\n\tWarning: Wanpipe Setup installation script uses the patch"
		echo -e "\t           command to update the kernel source in"
		echo -e "\t           $SOURCEDIR.  Please install patch before"
		echo -e "\t           proceeding."
	fi
	
	pause

	return 0
}

# ----------------------------------------------------------------------------
# Verify files and fix permissions.
# ----------------------------------------------------------------------------
fix_perms()
{
	echo -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
		case $TYPE in
		d)	
			[ -d /$TARGET ] || {
				continue
			}
			;;
		f)	
			[ -f /$TARGET ] || {
				continue
			}
			;;
		*)	continue
			;;
		esac
		chmod $MODE /$TARGET
		chown $OWNER /$TARGET
		chgrp $GROUP /$TARGET
		#echo "Ok."
	done < $FILELIST
	echo "Done";
	return 0
}



apply_pre_211_fix ()
{
	cp $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 WANPIPE kernel headers ..."
	
	cd $DRIVER_UPDATE_DIR/include/
	
	eval "cp *.h $SOURCEDIR/include/linux 2> /dev/null"
	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		return 1
	fi


	echo -n "Upgrading WANPIPE kernel drivers ..."
	
	cd $DRIVER_UPDATE_DIR/src/wanrouter
	
	eval "cp *.c $SOURCEDIR/$LINUXDRIVERS_WAN 2> /dev/null"
	if [ $? -ne 0 ]; then
		echo -e "Failed!\n"
		return 1
	fi

	cd $DRIVER_UPDATE_DIR/src/net

	eval "cp *.c $SOURCEDIR/$LINUXDRIVERS_NET 2> /dev/null"
	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		return 1
	fi

	#The latest release 2.2.3 and above contain two extra files
	#sdla_te1.c sdla_56k.c.  The kernel make files must be updated
	#when we perform the module updates.  

	cd $SOURCEDIR
	
	if [ $KPATCH -eq 2 ]; then 

		res=`grep sdla_56k.o drivers/net/Makefile` 
		if [ "$res" = "" ]; then
			echo "Updating $SOURCEDIR/drivers/net/Makefile"
			cp $PROD_HOME/patches/$MAKE_PATCH_22X .
			patch -p1 < $MAKE_PATCH_22X > /dev/null 2> /dev/null
			rm -f $MAKE_PATCH_22X
		fi
	
	elif [ $KPATCH -eq 4 ]; then

		res=`grep sdla_56k.o drivers/net/wan/Makefile` 
		if [ "$res" = "" ]; then

			echo "Updating $SOURCEDIR/drivers/net/wan/Makefile"

			if [ $KLVL -lt 4 ]; then
				cp $PROD_HOME/patches/$MAKE_PATCH_240 .
				patch -p1 < $MAKE_PATCH_240 > /dev/null 2> /dev/null
				rm -f $MAKE_PATCH_240
			else
				cp $PROD_HOME/patches/$MAKE_PATCH_244 .
				patch -p1 < $MAKE_PATCH_244 > /dev/null 2> /dev/null
				rm -f $MAKE_PATCH_244
			fi
		fi

		res=`grep af_wanpipe net/wanrouter/Makefile`
		if [ "$res" = "" ]; then
			echo "Updating $SOURCEDIR/net/wanrouter/Makefile"
			cp $PROD_HOME/patches/$AF_WANPIPE_MAKE_PATCH_24X .
			patch -p1 < $AF_WANPIPE_MAKE_PATCH_24X > /dev/null 2> /dev/null
			rm -f $AF_WANPIPE_MAKE_PATCH_24X
		fi
	fi

	cd $PROD_HOME	
	return 0
}

get_kernel_ver ()
{
	local tmp_ifs=$IFS
	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

	IFS=$tmp_ifs
}

apply_2422_fix()
{
	if [ $KVER -eq 2 ] && [ $KPATCH -eq 4 ]; then
	
		if [ $KLVL -eq 2 ]; then
		cp -f $SOURCEDIR/include/net/syncppp.h $SOURCEDIR/drivers/net/wan/syncppp.h > /dev/null 2> /dev/null 
		fi

		if [ $KLVL -eq 3 ]; then
		cp -f $SOURCEDIR/include/net/syncppp.h $SOURCEDIR/drivers/net/wan/syncppp.h > /dev/null 2> /dev/null  
		fi
	fi
}


apply_syncppp()
{
	if [ $KVER -eq 2 ]
	then
		if [ $KPATCH -eq 2 ]; then
			if [ $KLVL -lt 16 ]; then
				cp -f $DRIVER_UPDATE_DIR/syncppp/syncppp.2215.c $SOURCEDIR/drivers/net/syncppp.c
			else
				echo "Updating Syncppp for 2217 or greater";
				cp -f $DRIVER_UPDATE_DIR/syncppp/syncppp.2217.c $SOURCEDIR/drivers/net/syncppp.c
			fi
		elif [ $KPATCH -eq 4 ]; then
			if [ $KLVL -lt 3 ]; then
			cp -f $DRIVER_UPDATE_DIR/syncppp/syncppp.240.c $SOURCEDIR/drivers/net/wan/syncppp.c
			else
			cp -f $DRIVER_UPDATE_DIR/syncppp/syncppp.243.c $SOURCEDIR/drivers/net/wan/syncppp.c	
			fi
		fi
	fi
}



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

	banner
	cat << ENDOFTEXT

UPDATING WANPIPE DEVICE DRIVERS: LINUX KERNEL

To integrate WANPIPE Multiprotocol WAN Router (and WAN drivers 
included with this package) into the Linux kernel, the kernel has 
to be 'patched'. Patching will update WANPIPE source files 
located in the Linux kernel as well as modify two kernel source
files:
	1) $SOURCEDIR/net/sock.h
	2) $SOURCEDIR/include/linux/socket.h

If the kernel has already been patched with old WANPIPE 
drivers you'll be prompted to upgrade to the current version. 

ENDOFTEXT

	getyn "Would you like to apply kernel patches / upgrade drivers?" || return 0

	if [ $WITH_LINUX_OP = NO ]; then
		echo -e "\nPlease specify absolute path name of your linux directory"
		echo -e "\n\t(Press Enter for Default: /usr/src/linux)\n"
		if test -z $NONINTERACTIVE; then
			read response

			[ $response ] && {
				SOURCEDIR=$response
			}
		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 WANPIPE 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

	#The syncppp causes compilation problems in some
	#kernels thus remove it for now.
	#apply_syncppp
	
	apply_2422_fix
	
	#If the kernel has already been patched, offer an
	#upgrade option.
	check_kernel_patch_level $SOURCEDIR 
	if [ $? -ne 0 ]; then 
		echo
		echo "The kernel source in $SOURCEDIR has already been patched!"
		getyn "Would you like to upgrade WANPIPE to the current version ?" || return 0 

		update_wanpipe_drivers
		if [ $? -ne 0 ]; then
			echo "
ERROR: Failed to upgrade WANPIPE 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 "WANPIPE 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 || {
		if test -z $NONINTERACTIVE; then
			getyn "\nWould you like to continue?" || return 1
			search_rej
			rm $SOURCEDIR/$PATCH
		else
			echo "ERROR: Patching failed!"
			echo "The kernel source used is not supported!"
			echo "Call Sangoma at 905-474-1990 or use an older kernel"
			return 1
		fi
		return 0
	}
	rm $SOURCEDIR/$PATCH

	update_wanpipe_drivers
	if [ $? -ne 0 ]; then
		echo "
ERROR: Failed to patch WANPIPE 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

	search_rej

	return 0
}

# ----------------------------------------------------------------------------
# Install configuration files.
# ----------------------------------------------------------------------------
install_config()
{
	banner
	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

	return 0
}


function get_conf_dir ()
{
	local response 

	#banner
	if test -z $NONINTERACTIVE; then
		echo -e "\nPlease specify a desired location for WANPIPE 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_intr_dir ()
{
	local response=no
	local response1

	WAN_INTR_DIR=/etc/wanpipe/interfaces

	if [ ! -d $WAN_INTR_DIR ]; then
		\mkdir $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 wanpipe1]; 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
	elif    [ -d /var/lock ]; then
		LOCK_FILE=/var/lock/$PROD
	else	
		LOCK_FILE=/etc/wanpipe/$PROD.lck
	fi

	[ -f $META_CONF ] &&  mv $META_CONF $META_CONF.old 

	get_conf_dir
	get_intr_dir

	if [ $KERN_VER -ne 20 ]; then
	
		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 

	else
		ENABLE_IP_FWD=NO	
	fi

	if test $NONINTERACTIVE; then
		ENABLE_IP_FWD=NO
	fi

	cat > $META_CONF << ENDOFTEXT
#!/bin/sh
# 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).
#               WANPIPE_CONF_DIR=       Where to put wanpipe config files.
#		WANPIPE_INTR_DIR=	Where to put wanpipe interface files.
#               ROUTER_LOG=             Where to put start-up log file.
#               ROUTER_LOCK=            File used as a lock.
#		ROUTER_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 "WANPIPE_CONF_DIR=$WAN_CONF_DIR" >> $META_CONF
	echo "WANPIPE_INTR_DIR=$WAN_INTR_DIR" >> $META_CONF
	echo "ROUTER_LOG=$LOG_FILE"	>> $META_CONF
	echo "ROUTER_LOCK=$LOCK_FILE"	>> $META_CONF
	echo "ROUTER_IP_FORWARD=$ENABLE_IP_FWD" >> $META_CONF
	echo "NEW_IF_TYPE=$NEW_IF_TYPE" >> $META_CONF
	echo "WANCFG_LIB=/usr/lib/wanpipe/wancfg/lib" >> $META_CONF
	echo "WAN_DEVICES=\"wanpipe1\""	>> $META_CONF

	return 0
}

# ----------------------------------------------------------------------------
# Install initialization scripts.
# ----------------------------------------------------------------------------
install_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

	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 $ROOT/$WANROUTER_STARTUP $ROOT/$RC_DIR/rc2.d/$START_SCRIPT
		[ -d $RC_DIR/rc3.d ] && install -D -m 755 $ROOT/$WANROUTER_STARTUP $ROOT/$RC_DIR/rc3.d/$START_SCRIPT
		[ -d $RC_DIR/rc4.d ] && install -D -m 755 $ROOT/$WANROUTER_STARTUP $ROOT/$RC_DIR/rc4.d/$START_SCRIPT
		[ -d $RC_DIR/rc5.d ] && install -D -m 755 $ROOT/$WANROUTER_STARTUP $ROOT/$RC_DIR/rc5.d/$START_SCRIPT

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

	pause
	return 0

}

# ----------------------------------------------------------------------------
# Remove product.
# ----------------------------------------------------------------------------
remove()
{
	banner
	echo "You are about to wipe out Multiprotocol WAN Router!"
	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 "Router appears to be running. Stop it first"
		return 1
	}

	# 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
	WAN_LIST=`ls /etc/wanpipe?.conf`
	for wan in $WAN_LIST; do
		[ -f "$wan" ] && rm -f $wan
	done

	# 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
	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
	cat << ENDOFTEXT
WANPIPE UTILITIES SETUP

WANPIPE utilities are used to:
	1) create WANPIPE configuration files.
		(/usr/sbin/wancfg)
	2) startup and stop individal/all WANPIPE devices.
		(/usr/sbin/wanrouter)
	3) dynamically re-configure an individual/all WANPIPE device.
		(/usr/sbin/wanconfig)
	4) debug line, protocol and driver problems.
		(/usr/sbin/Xpipemon X={c,p,f,x ...})
	5) configure the optional onboard CSU/DSU.
		(/usr/sbin/cfgft1)
	6) aid in WANPIPE API development
		(/usr/lib/wanpipe/api)

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

ENDOFTEXT

	pause

	[ -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 [ ! -e $SOURCEDIR/include/asm ]; 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

	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


	echo
	echo -n "Compiling WANPIPE Utilities ..."

	cd $UTIL_DIR 

	delete_old_tools;

	cd $UTIL_DIR

	#Compiling the utilities
	eval "make SYSINC=$SOURCEDIR/include > /dev/null"
	if [ $? -eq 0 ]
	then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		echo -e "\n\t\t!!! WANPIPE Tools Compilation Failed !!!"
		echo -e "\tPossible solution:"
		echo -e "\t\t Wanpipe header files were not installed properly"
		echo -e "\t\t in $SOURCEDIR/include directory"
		echo -e "\tPlease contact Sangoma Tech. at 905 474-1990\n"
		pause
		return 1
	fi

	# If we are not in a RedHat System 
        # recompile all utilities.
	echo -n "Compiling WANPIPE Configuration Utilities ..."

	cd $PROD_HOME/config
	
	eval "make SYSINC=$SOURCEDIR/include > /dev/null"
	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
		echo -e "\tERROR: Failed to compile WANPIPE configuration utilities !!!"
		echo -e "\tPossible Causes:  1) Ncurses libraries are not installed"
		echo -e "\t\nPlease contact Sangoma Technologies"
		pause
		return 0
	fi


	#The release for 2.0.X kernels doesn't support API utilities.
	if [ $KERN_VER -ne 20 ] ; then
		echo -n "Compiling WANPIPE API Development Utilities ..."

		cd $PROD_HOME/api
		eval "make SYSINC=$SOURCEDIR/include > /dev/null"
		if [ $? -eq 0 ]; then
			echo -e "Done.\n"
		else
			echo -e "Failed!\n"
			echo -e "\tERROR: Failed to compile WANPIPE API Tools !!!"
			echo -e "\t\nPlease contact Sangoma Technologies"
			pause
			return 0
		fi
	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/config
	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 compile_drivers ()
{

	banner
	cat << ENDOFTEXT
WANPIPE KERNEL DRIVER SETUP
	
The next step in WANPIPE installation involves compiling WANPIPE kernel
modules.  The setup is able to compile all WANPIPE and API drivers.

	Thus, NO kernel recompilation is necessary :)

WANPIPE drivers will be compiled for all protocols as well as
API and Educational support. If further optimization is required 
please compile WANPIPE drivers manually. 

Refer to the WapipeIntallation.(pdf/txt) documentation.
ENDOFTEXT

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

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

	get_kernel_ver $SOURCEDIR

	echo
	getyn "Proceed to build WANPIPE kernel modules ?" || return 0;
	if [ ! -d $DRIVER_TMP_DIR ]; then
		eval "\mkdir $DRIVER_TMP_DIR > /dev/null"
		if [ $? -ne 0 ]; then
			echo "ERROR: Failed to create $DRIVER_TMP_DIR directory!!!"
			pause
			return 0
		fi
	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


	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 "       Driver compilation must be performed manually"
		echo "       after the kernel is configured and compiled"
		echo
		echo "       Please refer to the WanpipeInstallation.(pdf/txt) on how"
		echo "       to configure and compile a fresh linux kernel."
		pause
		return 0
	fi

	if [ ! -f $SOURCEDIR/include/linux/modversions.h ] && [ $KERN_VER -ne 20 ]; then
		echo -e "\n"
		echo "ERROR: The $SOURCEDIR contains a fresh, unconfigured kernel!"
		echo "       Driver compilation must be performed manually"
		echo "       after the kernel is configured and compiled"
		echo
		echo "       Please refer to the WanpipeInstallation.(pdf/txt) on how"
		echo "       to configure and compile a fresh linux kernel."
		pause
		return 0
	fi

	eval "grep \"define *CONFIG_WAN_ROUTER *1\" $SOURCEDIR/include/linux/autoconf.h > /dev/null"
	if [ $? -eq 0 ]; then
		echo -e "\n"
		echo "ERROR: The WANPIPE 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 "       Driver compilation must be performed manually"
		echo "       after the kernel is re-configured and re-compiled"
		echo
		echo "       Please refer to the WanpipeInstallation.(pdf/txt) on how"
		echo "       to configure and compile a fresh linux kernel."
		pause
		return 0
	fi


	eval "grep \"define *CONFIG_MODVERSIONS\" $SOURCEDIR/include/linux/autoconf.h > /dev/null"
	if [ $? -eq 0 ]; then
		MODVER=" -DMODVERSIONS -include $SOURCEDIR/include/linux/modversions.h "
	else	
		MODVER=""
	fi

	apply_2422_fix

	cd $DRIVER_TMP_DIR

	#Copy the WANPIPE device drivers from $SOURCEDIR
	#into a temporary directory

	for file in $DRIVERS_NET
	do	
	
		if [ $KERN_VER -eq 24 ]; then

			if [ $file = syncppp.h ]; then
				if [ $KLVL -ge 3 ]; then
					continue
				fi
			fi
		fi
	
		if [ ! -f "$SOURCEDIR/$LINUXDRIVERS_NET/$file" ]; then 
			echo
			echo "
ERROR: File not found $SOURCEDIR/$LINUXDRIVERS_NET/$file!!!
			
Make sure that the kernel source has been
patched with the latest WANPIPE patches!"
			pause
			return 0
		fi

		cp $SOURCEDIR/$LINUXDRIVERS_NET/$file .
	done

	for file in $DRIVERS_WAN
	do	
		if [ ! -f "$SOURCEDIR/$LINUXDRIVERS_WAN/$file" ]; then 
			echo
			echo "
ERROR: File not found $SOURCEDIR/$LINUXDRIVERS_WAN/$file!!!
			
Make sure that the kernel source has been
patched with the latest WANPIPE patches!"
			pause
			return 0
		fi

		cp $SOURCEDIR/$LINUXDRIVERS_WAN/$file .
	done

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

	echo -e "\n\tSupported WAN Protocols:\n"
	cat << ENDOFTEXT
1. Frame Relay 
	Support for frame relay routing, API, or 
	bridging.
	
2. Cisco HDLC 
	Support for Dual Port Cisco HDLC routing 
	API, and TTY PPP over HDLC Streaming on 
	S514-PCI/S508-ISA cards.
	
3. PPP
	Support for PPP routing on S514-PCI/S508-ISA cards.

ENDOFTEXT

	if [ $KERN_VER -ne 20 ]; then
		cat << ENDOFTEXT
4. Multi-Port PPP
	Support for kernel SyncPPP over	HDLC streaming. 
	This option can support a syncppp link
	on each Sangoma adapter (S514-PCI/S508-ISE) port.

5. X25 
	Support for X25 routing and API on S514 and S508
	cards.

6. API Socket
	Support for X25, HDLC, CHDLC and Frame Relay API
	socket development.
ENDOFTEXT
	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;
			fi
			echo
                fi
        fi

	echo
	echo -n "Checking for SMP support ..."
	eval "grep \"CONFIG_SMP *1\" $SOURCEDIR/include/linux/autoconf.h > /dev/null"
	if [ $? -eq 0 ]; then
		echo -e "Enabled.\n"
		CONFIG_SMP=YES;
	else	
		echo -e "Disabled.\n"
		CONFIG_SMP=NO;
	fi

	#Find out our processor type. This is needed to properly
	#compile our modules.
	echo -n "Checking current processor type ..."
	ARCH=${ARCH:-i686};
	echo -e "$ARCH\n"

	#Setup the COMPILATOIN FLAGS depending on the kenrel type
	if [ $KERN_VER -eq 24 ]; then
		echo -n "Compiling General WANPIPE Driver for 2.4.X Kernel ."
		CFLAGS="$CC -D__KERNEL__ -I$SOURCEDIR/include -Wall -Wstrict-prototypes -O2 -fomit-frame-pointer -fno-strict-aliasing -pipe -march=$ARCH -DMODULE -DEXPORT_SYMTAB"

		#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


	elif [ $KERN_VER -eq 22 ]; then
		echo -n "Compiling General WANPIPE Driver for 2.2.X Kernel ."
		ARCH=${ARCH#i}
		CFLAGS="$CC -D__KERNEL__ -I$SOURCEDIR/include -Wall -Wstrict-prototypes -O2 -fomit-frame-pointer -fno-strict-aliasing -pipe -fno-strength-reduce -m486 -malign-loops=2 -malign-jumps=2 -malign-functions=2 -DCPU=$ARCH -DMODULE -DEXPORT_SYMTAB"
	else
		echo -n "Compiling General WANPIPE Driver for 2.0.X Kernel ."
		ARCH=${ARCH#i}
		CFLAGS="$CC -D__KERNEL__ -I$SOURCEDIR/include -Wall -Wstrict-prototypes -O2 -fomit-frame-pointer -fno-strength-reduce -pipe -m486 -malign-loops=2 -malign-jumps=2 -malign-functions=2 -DCPU=$ARCH -DMODULE"
	fi

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

	CFLAGS="$CFLAGS $MODVER"

	#Compile all individual protocols first

	eval "$CFLAGS -DCONFIG_ALL_WANPIPE_PROT -c -o tmp/wanmain.o wanmain.c"
	eval "$CFLAGS -c -o tmp/wanproc.o wanproc.c"
	eval "ld -r -o mod/wanrouter.o tmp/wanmain.o tmp/wanproc.o"
	eval "$CFLAGS -c -o mod/af_wanpipe.o af_wanpipe.c"

	echo -n "."

	eval "$CFLAGS -c -o tmp/sdla_fr.o sdla_fr.c"
	eval "$CFLAGS -c -o tmp/sdla_chdlc.o sdla_chdlc.c"
	eval "$CFLAGS -c -o tmp/sdla_ppp.o sdla_ppp.c"

	echo -n "."

	if [ $KERN_VER -ne 20 ]; then
		eval "$CFLAGS -c -o tmp/sdla_x25.o sdla_x25.c"
		eval "$CFLAGS -c -o tmp/wanpipe_multppp.o wanpipe_multppp.c"
		eval "$CFLAGS -c -o mod/syncppp.o syncppp.c"
		eval "$CFLAGS -c -o tmp/sdla_bitstrm.o sdla_bitstrm.c"
		eval "$CFLAGS -c -o tmp/sdla_edu.o sdla_edu.c"
		eval "$CFLAGS -c -o tmp/sdla_bsc.o sdla_bsc.c"
	fi

	echo -n "."

	eval "$CFLAGS -c -o tmp/sdla_56k.o sdla_56k.c"
	eval "$CFLAGS -c -o tmp/sdla_te1.o sdla_te1.c"
	eval "$CFLAGS -c -o tmp/sdla_ft1.o sdla_ft1.c"
	eval "$CFLAGS -c -o mod/sdladrv.o sdladrv.c"
	
	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
	fi

	LFLAGS="ld -r -o mod/wanpipe.o tmp/sdlamain.o tmp/sdla_ft1.o tmp/sdla_te1.o tmp/sdla_56k.o"


	#Link in appropriate protocols as needed.

	echo -n "Compiling Wanpipe Driver for all protocols ..."
	
	if [ $KERN_VER -eq 20 ]; then
		eval "$CFLAGS -DCONFIG_ALL_WANPIPE_PROT \
			-c -o tmp/sdlamain.o sdlamain.c"

		eval "$LFLAGS tmp/sdla_fr.o tmp/sdla_chdlc.o tmp/sdla_ppp.o"
	else	
		eval "$CFLAGS -DCONFIG_ALL_WANPIPE_PROT \
			-c -o tmp/sdlamain.o sdlamain.c"

		eval "$LFLAGS tmp/sdla_fr.o tmp/sdla_chdlc.o tmp/sdla_ppp.o \
		               tmp/wanpipe_multppp.o tmp/sdla_x25.o tmp/sdla_bitstrm.o tmp/sdla_edu.o tmp/sdla_bsc.o"
	fi
	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
	fi

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


	if [ $KERN_VER -eq 24 ]; then
	   install -D -m 644 mod/sdladrv.o $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/sdladrv.o
	   install -D -m 644 mod/wanpipe.o $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/wanpipe.o
	   install -D -m 644 mod/wanrouter.o $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/wanrouter.o
	   install -D -m 644 mod/af_wanpipe.o $ROOT/lib/modules/$KERNEL_VERSION/kernel/net/wanrouter/af_wanpipe.o
	   install -D -m 644 mod/syncppp.o   $ROOT/lib/modules/$KERNEL_VERSION/kernel/drivers/net/wan/syncppp.o 
	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 [ $KERN_VER -ne 20 ]; then
	   	install -D -m 644 mod/syncppp.o   $ROOT/lib/modules/$KERNEL_VERSION/net/syncppp.o
	   fi
	fi

	if [ $? -eq 0 ]; then
		echo -e "Done.\n"
	else
		echo -e "Failed!\n"
	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 "ERROR: Module dependencies failed!"
				echo "       This usually means that the Linux source located in"
				echo "       $SOURCEDIR was not used to build the image currently" 
				echo "       running on this machine."
				echo
				echo "       Please proceed to manually recompile the kernel"
				echo "       and kernel modules. Refer to WanpipeInstallation.(pdf/txt)"
				echo "       for more information."
				rm -f $PROD_HOME/tmp.$$
				if [ -d "$DRIVER_TMP_DIR" ]; then
					rm -rf $DRIVER_TMP_DIR 
				fi
				pause
				return 
			fi
			rm -f $PROD_HOME/tmp.$$
		fi
	fi

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

	pause
}

function install_all ()
{
	echo "Installing WANPIPE Files ... !"

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

	echo "Installing Wanpipe Utilities in $ROOT/usr/sbin"
	cd $PROD_HOME/config
	make install WAN_VIRTUAL=$ROOT > /dev/null 2> /dev/null

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

	install -D -m 755 $PROD_HOME/util/wanpipe_setup $ROOT/usr/sbin/wanpipe_setup
	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/usr/lib/wanpipe"
	
	\mkdir -p $ROOT/usr/lib/wanpipe/wancfg/lib/
	\cp -f $PROD_HOME/config/wancfg/lib/* $ROOT/usr/lib/wanpipe/wancfg/lib/
	install -D -m 755 $PROD_HOME/config/wancfg/pppconfig $ROOT/usr/sbin/wp_pppconfig
	
	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/usr/lib/wanpipe/api"
	\cp -rf api $ROOT/usr/lib/wanpipe
	\cp -rf samples $ROOT/etc/wanpipe

	pause
	return 0
}

function uninstall_all ()
{
	echo "Uninstalling WANPIPE Binaries!\n"

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


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


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

	pause
	return 0
}



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

PATH=/bin:/sbin:/usr/bin:/usr/sbin
KERNEL_VERSION=`uname -r`
KERNEL_UNAME=`uname -r`
PROD=wanrouter
PROD_VER=beta3-2.2.4
PROD_HOME=`pwd`
META_CONF=$PROD_HOME/$PROD.rc
WAN_INTR_DIR=$PROD_HOME/interfaces
WAN_CONF_DIR=$PROD_HOME
PROD_CONF=$WAN_CONF_DIR/wanpipe1.conf
PROD_PATCH=$PROD_HOME/patches
PROD_INIT=/usr/sbin/
FILELIST=$PROD_HOME/Filelist
SOURCEDIR=/usr/src/linux
START_SCRIPT=S20$PROD
OLD_START=S20router
STOP_SCRIPT=K10$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 cpipemon fpipemon ppipemon xpipemon wpkbdmon wpbackupd"
WANROUTER_STARTUP_SMPL=$PROD_HOME/samples/wanrouter
WANROUTER_STARTUP=/usr/sbin/wanrouter
DRIVERS_NET="sdladrv.c sdlamain.c sdla_ft1.c sdla_te1.c sdla_56k.c sdla_chdlc.c sdla_fr.c sdla_ppp.c sdla_x25.c wanpipe_multppp.c syncppp.h syncppp.c sdla_bitstrm.c sdla_edu.c sdla_bsc.c"
DRIVERS_WAN="wanmain.c wanproc.c af_wanpipe.c"
DRIVER_UPDATE_DIR=$PROD_PATCH/kdrivers
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"
AF_WANPIPE_MAKE_PATCH_24X="makefile.af_wanpipe.patch"

TEMP=$PROD_HOME/temp.$$
WANCFG=$PROD_HOME/config/wancfg/wancfg
CFGFT1=$PROD_HOME/config/ft1/cfgft1

CC=gcc

ROOT=;

WITH_LINUX_OP="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"
else
	KERN_VER=22
	LINUXDRIVERS_NET="drivers/net"
	
	eval "uname -r | grep 2.0 > /dev/null"
	if [ $? -eq 0 ]; then
		KERN_VER=20
		DRIVERS_NET="sdladrv.c sdlamain.c sdla_ft1.c sdla_chdlc.c sdla_fr.c sdla_ppp.c sdla_x25.c"
	fi
fi
LINUXDRIVERS_WAN="net/wanrouter"

[ "$UID" = 0 ] || {
	error "You must be a superuser (root) to run this script"
	exit 1
}

# Check router home directory.
[ -d "$PROD_HOME" ] || {
	error "Router home directory ($PROD_HOME) not found"
	exit 1
}

NONINTERACTIVE=;
setup_cmd=$1;

while [ ! -z "$2" ]
do
	tmp_val=$2;
	
	case $tmp_val in

	silent*)
		NONINTERACTIVE=1;
		;;
	--with-linux*)
		SOURCEDIR=`echo $2 | cut -d'=' -f2`;
		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";
		;;
	--builddir*)
		ROOT=`echo $2 | 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
		;;
	--arch*)
		ARCH=`echo $2 | cut -d'=' -f2`;

		if [ $ARCH != "i686" ] && [ $ARCH != "i586" ]; then
			echo "Error: Invalid Architecture [i686|i586]\n"
			exit 1;
		fi
		;;
	*)
		echo "Invalid option $2"
		exit 1;
		;;
	esac

	shift;
done


if [ "$setup_cmd" = "remove" ]; then 
	remove; 
	uninstall_all
	exit; 
fi

if [ "$setup_cmd" = "upgrade" ]; then
	prepare || exit 1
	apply_patches || exit 1
	compile_drivers
	compile_src
	install_all
	exit; 
fi

if [ "$setup_cmd" = "drivers" ]; then
	apply_patches || exit 1
	compile_drivers
	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" ]; then

	if [ -d $PROD_HOME/rpmbuild ]; then
		\rm -rf $PROD_HOME/rpmbuild > /dev/null 2> /dev/null
	fi

	\mkdir -p $PROD_HOME/rpmbuild	
	
	$PROD_HOME/Setup install silent --builddir=$PROD_HOME/rpmbuild --with-linux=$SOURCEDIR --arch=$ARCH
	if [ $? -ne 0 ]; then
		echo "Error: WANPIPE Installation Failed!"
		exit 1;
	fi
	
	rpm -ba --root $PROD_HOME/rpmbuild $PROD_HOME/rpmspec/wanpipe.spec
	if [ $? -eq 0 ]; then
		cat <<ENDOFTEXT

WANPIPE RPM BUILD SUCCESSFUL

The new rpm is located in /usr/src/redhat/RPMS/i386
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

	if [ -d $PROD_HOME/rpmbuild ]; then
		rm -rf $PROD_HOME/rpmbuild > /dev/null 2> /dev/null
	fi
	exit 0;
fi

if [ "$1" = "helprpm" ]; then
	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 /usr/src/linux.

	1. The absolute path must point to a
	   configured (.config file must exist)
	   kernel source.  If path is not supplied
	   it's defaulted to /usr/src/linux.

	2. The RPM will be build in a virtual
	   directory called $PROD_HOME/rpmbuild/. Thus, it
	   will not polute 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 or i586.
	   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 $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.


ENDOFTEXT
	exit 0;
fi


if [ "$setup_cmd" != "install" ]; then
	cat <<ENDOFTEXT
USAGE:
======

./Setup {command}  
./Setup {command} [ silent ] [ --builddir=<abs pth> ]	\\ 
                             [ --with-linux=<abs pth> ] \\
		             [ --arch=<custom arch> ]
	
	commands:
	---------
	install  : Install WANPIPE
	upgrade  : Upgrade WANPIPE kernel device drivers
		   and utilities.
	remove   : Uninstall WANPIPE
	utility  : Re-compile WANPIPE Tools/Utilities
	drivers  : Re-install and Re-compile
		   WANPIPE kernel device drivers
	buildrpm : Build the custom RPM binary for the
	           current system.  
		   For further help read README.rpm
	helprpm  : RPM build help information.
	<any key>: Help

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

	silent	    : Non interactive. Install using default
	              values. Disabled by default.
		      
	--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 /usr/src/linux
		      eg: --with-linux=/usr/src/linux-2.4.4

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

ENDOFTEXT
	exit 1;
fi	


welcome || exit 0
prepare	|| exit 1
apply_patches || exit 1
compile_drivers 
install_init || exit 1
install_config || exit 1
compile_src || exit 1
install_all 
clean_up 

goodbye

