#!/bin/sh
# Setup		WAN Router Installation/Removal Script.
#
# Copyright	(c) 1996-2000, 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.
# ----------------------------------------------------------------------------
# Feb 29, 2000  Nenad Corbic    Removed print statmetnts 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()
{
	# check if the terminal environment is set up
	[ "$TERM" ] && clear 2> /dev/null
}

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

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

# ----------------------------------------------------------------------------
# Prompt user for input.
# ----------------------------------------------------------------------------
prompt()
{
	echo -ne "$*" >&2
	read CMD rest
	return 0
}

# ----------------------------------------------------------------------------
# Get Yes/No
# ----------------------------------------------------------------------------
getyn()
{
	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-2000, Sangoma Technologies Inc."
	echo -e "\t----------------------------------------------------------"
	echo ""
	return 0
}

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

WARNING:
You must have the full Linux source code and development system (i.e. GNU C
compiler and utilities) installed in order to be able to install this product.
You should also be prepared to re-configure and re-compile your Linux kernel
after the installation is complete.

Please read WAN Router User's Manual and Release Notes before proceeding with
the installation.

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

# ----------------------------------------------------------------------------
# Goodbye.
# ----------------------------------------------------------------------------
goodbye()
{
	banner
	cat <<ENDOFTEXT
WAN Router installation is now complete.  If kernel patches were successfully
applied during the installation, then you have to rebuild Linux kernel.
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 zlilo' or 'make 'bzImage')
	4) build modules with 'make modules'
	5) install modules with 'make modules_install'
	6) build WANPIPE Tools with './Setup compile' (from $PROD_HOME)
	6) re-boot your system and load the new kernel !

Please read WAN Router User's Manual before configuring Linux kernel.  For
more information about re-compiling the kernel refer to README file found in
/usr/src/linux directory.

ENDOFTEXT
}

# ----------------------------------------------------------------------------
# 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
	}
	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)	#echo -n "Directory $TARGET "
			[ -d /$TARGET ] || {
				echo "not found!"
				return 1
			}
			;;
		f)	#echo -n "File $TARGET "
			[ -f /$TARGET ] || {
				echo "not found!"
				return 1
			}
			;;
		*)	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
}



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

	banner
	cat << ENDOFTEXT
To integrate Multiprotocol WAN Router (and WAN drivers included with this
package) into the Linux kernel, it has to be 'patched'.  During this step
router source files will be added to the Linux source tree and necessary
modifications are made to some kernel source files.  See doc/patches.txt
for more information.

ENDOFTEXT

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

 	echo -e "\nPlease specify absolute path name of your linux directory"
	echo -e "\n\t(Press Enter for Default: /usr/src/linux)\n"
	read response

	[ $response ] && {

		SOURCEDIR=$response
	}

        echo -e "\nSetting linux directory to $SOURCEDIR\n";

	# 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 manually after
you install kernel source.

ENDOFTEXT

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

	check_kernel_patch_level $SOURCEDIR || {
			echo -e "\n\tThis kernel source has already been patched";
			echo -e "\tPlease use a fresh kernel !!\n";
			pause;
			return 0;
			}

	fgrep "PATCHLEVEL = 0" $SOURCEDIR/Makefile > /dev/null
	if [ $? -eq 0 ]
	then 
		#Patch a 2.0 kernel
		echo -e "\n\t2.0.X Kernel Detected:  Patching a 2.0.X Kernel !!\n"
		PATCH=$PROD-v20.gz 
 		[ -f $PATCH ] || { getyn "Patch file missing $PATCH, Continue?";
				   return; }
	else

		#patch a 2.2 kernel
		PATCH=$PROD-v2214.gz
		echo -e "\n\t2.2.X Kernel Detected:  Patching a 2.2.X Kernel !!\n"
		[ -f $PATCH ] || { getyn "Patch file missing $PATCH, Continue?"; 
				  return; }

		fgrep "SUBLEVEL = 1" $SOURCEDIR/Makefile  > /dev/null
		if [ $? -eq 0 ]; then
			fgrep "SUBLEVEL = 10" $SOURCEDIR/Makefile  > /dev/null
			if [ $? -ne 0 ]; then
				before_14=0;
				fgrep "SUBLEVEL = 11" $SOURCEDIR/Makefile  > /dev/null
				if [ $? -eq 0 ]; then
					before_14=11;
				fi
				fgrep "SUBLEVEL = 12" $SOURCEDIR/Makefile  > /dev/null
				if [ $? -eq 0 ]; then
					before_14=12;
				fi
				fgrep "SUBLEVEL = 13" $SOURCEDIR/Makefile  > /dev/null
				if [ $? -eq 0 ]; then
					before_14=13;
				fi


				if [ $before_14 -eq 0 ]; then
					echo "Patching kernel 2.2.14 or greater."
					PATCH=$PROD-v2214.gz
				else
					echo "Patching kernel 2.2.$before_14."
					PATCH=$PROD-v2213.gz
				fi

			else
				apply_pre_211_fix || return 1;
				PATCH=$PROD-v2213.gz
			fi	
		else
			apply_pre_211_fix || return 1;
			PATCH=$PROD-v2213.gz
		fi
	fi

	cp $PROD_PATCH/$PATCH $SOURCEDIR
	cd $SOURCEDIR
	gzip -cd $PATCH | patch -p1 || {
		getyn "\nWould you like to continue?" || return 1
		search_rej
		rm $SOURCEDIR/$PATCH
		return
	}
	rm $SOURCEDIR/$PATCH

	# 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
There are two configuration files associated with the WAN router.  One of
them, $META_CONF, is used by the router start-up script and defines
location of other files, such as start-up log file.  If you want to change
default names and locations of those files, you can edit $META_CONF.

Another configuration file, $PROD_CONF, defines WAN links and interfaces
and is used to configure WAN drivers.  As contents of this file is driver-
specific, the setup script will install only a template.  You will have to
edit this file according to your driver requirements.  Please read WAN
Router User's Manual and Configuration Reame file in $PROD_HOME/doc 
directory for more information.

ENDOFTEXT

	# Create meta-configuration file.
	create_mataconf

	return 0
}


function get_conf_dir ()
{
	local response 

	#banner
	echo -e "\nPlease specify a desired location for WANPIPE configuration files."
	echo -e "\n\t(Press Enter for Default: $PROD_HOME)\n"
	read response

	WAN_CONF_DIR=$PROD_HOME

	if [ $response ]; then 
		WAN_CONF_DIR=$response
	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=$PROD_HOME
		else 
			get_conf_dir	
		fi 
	fi
}

function get_intr_dir ()
{
	local response 

	#banner
	echo -e "\nPlease specify a desired location for WANPIPE interface files."
	echo -e "\n\t(Press Enter for Default: $PROD_HOME/interfaces)\n"
	read response

	WAN_INTR_DIR=$PROD_HOME/interfaces

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

	# 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=$PROD_HOME/interfaces
		else 
			get_intr_dir	
		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=$PROD_HOME/$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=$PROD_HOME/$PROD.lck
	fi

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

	get_conf_dir
	get_intr_dir
	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 /usr/local/wanrouter 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.
#               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
#                                       $WAN_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 "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
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.

ENDOFTEXT

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

#FIXME: Use this when adding X25API option
#
#	echo -e "\n\t Which would you like to startup on boot?"
#	echo -e "\t 1. WANPIPE "
#	echo -e "\t 2. X25API "
#	echo -e "\n\t Please choose 1 or 2 :"
#       while prompt "$*"
#        do      case $CMD in
#                        [1])    PROD_INIT=$PROD_INIT$PROD 
#                                echo -e "\n\t WANPIPE Setup for boot startup "
#                                break
#                                ;;
#                        [2])    PROD_INIT=$PROD_INIT$X25API 
#                                echo -e "\n\t X25API Setup for boot startup "
#                                break
#                                ;;
#                        *)      echo -e "\n\tPlease choose 1 or 2" >&2
#                                ;;
#                esac
#        done                 	 

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


	# 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/rc5.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

	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 /usr/src/linux"
    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

	echo -e "\n\tCompiling WANPIPE tools in $UTIL_DIR directory\n"
	cd $UTIL_DIR 

	[ -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 /usr/src/linux before"
                echo -e "\tproceeding"
		pause
	       	return 1 
	}

	[ -f $INCLUDE/autoconf.h -a -f $INCLUDE/version.h ] || {
		echo -e "\n\tKernel source has not been compiled !";
		echo -e "\tPlease compile the kernel and modules first before";
		echo -e "\tcompiling WANPIPE Tools";
		echo -e "\n\tOnce the kernel is successfully compiled, run";
		echo -e "\t'./Setup compile' from the $PROD_HOME directory to finish up";
		echo -e "\tthe WANPIPE Tools installation.\n";
		pause		
		return 0;
	}

	cd $UTIL_DIR 

	delete_old_tools;

	#Compiling the utilites

	exec make | grep "Ok\." > /dev/null	
	if [ $? -eq 0 ]
	then
		echo -e "\n\t\tWANPIPE Utilities Compiled OK"
		echo -e "\tWANPIPE Utilities have been installed successfully\n"
	else
		echo -e "\n\t\t!!! WANPIPE Tools Compilation Failed !!!"
		echo -e "\n\tIf you are running Red Hat, 2.2.X kernel try using the binary"
		echo -e "\ttools supplied by Sangoma, (Recommended)\n"
		getyn "\tWould you like to use binary tools supplied ?" || {
				echo -e "\n\tWARNING: Wanpipe Tools setup failed !!";
				echo -e "\tPlease contact Sangoma at (905) 474-1990\n";
				pause
				return 1;
		}

		cp $UTIL_BIN_DIR/* /usr/sbin	
		if [ $? -eq 0 ]
		then 	
			echo -e "\n\t\tWANPIPE Tools binaries installed successfully"
		else
			echo -e "\n\tERROR: Wanpipe Tools binaries failed to copy !"
			echo -e "\tPlease contact Sangoma Tech. at 905 474-1990\n"
			pause
			return 1
		fi
	fi

	# If we are not in a RedHat System 
        # recompile all utilities.

	echo -e "\n\tCompiling Configuration and API utilities !\n"

	cd $PROD_HOME/config
	
	exec make | grep "Ok\." > /dev/null	
	if [ $? -eq 0 ]; then
		echo -e "\tWANPIPE Configurator Tools Compiled OK\n"
	else
		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 1
	fi


	# Create Links to Configurtor utilites
	if [ ! -f "$PROD_HOME/cfgft1" ]; then
		ln -s $PROD_HOME/config/ft1/cfgft1 $PROD_HOME/cfgft1
	fi
	if [ ! -f "$PROD_HOME/wancfg" ]; then
		ln -s $PROD_HOME/config/wancfg/wancfg $PROD_HOME/wancfg
	fi


	cd $PROD_HOME/api
	exec make | grep "Ok\." > /dev/null	
	if [ $? -eq 0 ]; then
		echo -e "\tWANPIPE API Tools Compiled OK\n"
	else
		echo -e "\tERROR: Failed to compile WANPIPE API Tools !!!"
		echo -e "\t\nPlease contact Sangoma Technologies"
		pause
		return 1
	fi

	echo -e "\tWANPIPE Environment Setup Complete !!!\n"

	pause
	return 0
}

delete_old_tools()
{
	local tool
	local tool_exe

	for tool in $WAN_TOOLS; do
		tool_exe="/usr/sbin/$tool"
		[ -f "$tool_exe" ] && rm -f $tool_exe	
	done

	if [ -f "$PROD_HOME/config/ft1/source/ft1_exec" ]; then
		rm -f $PROD_HOME/config/ft1/source/ft1_exec 
	fi
	
	if [ -f "$PROD_HOME/config/lxdialog/lxdialog" ]; then
		rm -f $PROD_HOME/config/lxdialog/lxdialog
		rm -f $PROD_HOME/config/lxdialog/*.o
	fi

}

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 kernel patch is $val"
		if [ $val = "2.0.3" ]; then
			return 0
		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
}


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

PATH=/bin:/sbin:/usr/bin:/usr/sbin
KERNEL=`uname -r`
PROD=wanrouter
PROD_VER=2.1.3
PROD_HOME=/usr/local/$PROD
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=/usr/src/linux/include/linux
ROUTER_RC=$META_CONF
UTIL_DIR=$PROD_HOME/util
UTIL_BIN_DIR=$PROD_HOME/util/bin
FIX_211="Fix_below_2211.gz"
WAN_TOOLS="wanconfig sdladump cpipemon fpipemon ppipemon xpipemon"


trap '' 2

[ "$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
}

if [ "$1" = "remove" ]; then 
	remove; 
	exit; 
fi

if [ "$1" = "compile" ]; then
	compile_src; 
	exit; 
fi

if [ "$1" != "install" ];
then
	echo -e "\nUSAGE:";
	echo -e "   ./Setup {optons}";
	echo -e "\n            install  : Install WANPIPE"
	echo -e "            remove   : Uninstall WANPIPE";
	echo -e "            compile  : Compile WANPIPE Tools";
	echo -e "           <any key> : Help\n";
	exit 0;
fi	
		  
welcome || exit 0
prepare	|| exit 1
apply_patches || exit 1
install_init || exit 1
install_config || exit 1
compile_src || exit 1
clean_up 

goodbye

