#!/bin/sh
# Setup		WAN Router Installation/Removal Script.
#
# Copyright	(c) 1996-1999, 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.
# ----------------------------------------------------------------------------
# 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-1999, 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 /usr/src/linux
	2) configure kernel with 'make config' or '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 c' (from /usr/lib/router)
	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()
{
	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
	return 0
}

# ----------------------------------------------------------------------------
# Apply kernel patches.
# ----------------------------------------------------------------------------
apply_patches()
{
	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-v22.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
		[ $? -eq 0 ] && {
			fgrep "SUBLEVEL = 10" $SOURCEDIR/Makefile  > /dev/null
			[ $? -eq 0 ] || {
				cp $PROD_PATCH/$FIX.gz $SOURCEDIR
				cd $SOURCEDIR
				echo -e "Detecting Kernel greater than 2.2.10"
				gzip -cd $FIX.gz | patch -p1 || {
					echo -e "\nA fix for 2.2.11 (or greater) kernel has failed"
					echo -e "Contact Sangoma (905) 474-1990\n"
					rm $SOURCEDIR/$FIX.gz
					getyn "\nWould you like to continue?" || return 1
					return
				}
				rm $SOURCEDIR/$FIX.gz
			}
		}

	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

	[ -f $PROD_CONF ] || mv $PROD_CONF $PROD_CONF.old

	# Install sample router configuration file.

        echo -e "\n\t----------------------------------------------------------"
        echo -e "\t          WAN PROTOCOL CONFIGURATION OPTIONS " 
        echo -e "\t    Copyright (c) 1995-1999, Sangoma Technologies Inc."
        echo -e "\t----------------------------------------------------------\n"
	echo -e "\t1.  Frame Relay    (FR)"
	echo -e "\t2.  Cisco HDLC     (CHDLC)"
	echo -e "\t3.  Point to Point (PPP)"
	echo -e "\t4.  Multiple devices/protocols"
	echo -e "\nPlease choose a protocol (1 to 4): "
        while prompt "$*"
        do      case $CMD in
                        [1])    cp $PROD_HOME/samples/wanpipe1.fr $PROD_CONF 
				echo -e "\n\tFrame relay setup in $PROD_CONF"
	 			break			
                                ;;
                        [2])    cp $PROD_HOME/samples/wanpipe1.ppp $PROD_CONF 
				echo -e "\n\tPPP setup in $PROD_CONF"
				break
                                ;;
			[3])    cp $PROD_HOME/samples/wanpipe1.cpri $PROD_CONF
				echo -e "\n\tCHDLC Primary Port Setup in $PROD_CONF"
				break
				;;
#			[4])    cp $PROD_HOME/samples/router.x25 $PROD_CONF
#				echo -e "\n\tX25 setup in /etc/router.conf"
#				break
#				;;
			[4])    echo -e "\n\tWarning: Your configuration files have not been"
				echo -e   "\t                     installed !" 
				echo -e "\n\tPlease read the Configuration Readme file"
				echo -e "\tin $PROD_HOME/doc/WANPIPE_CONFIG.txt, on how"
				echo -e "\tto configure Sangoma WANPIPE router for"
				echo -e "\tmultiple devices and protocols !"
				pause "\n\tPress any key to complete the installation\n"
				return 0
				break
				;;
                        *)      echo -e "\n\tPlease choose 1,2,3 or 4" >&2
                                ;;
                esac
        done                   

#	echo -e "\n\tX25API setup in /etc/x25api.conf"
#	cp $PROD_HOME/samples/x25api.conf $X25API_CONF

	echo -e "\n\tPlease read the Wanpipe Router Configuration file on how to"
	echo -e "\tcorrectly configure your router."
	echo -e "\tThe file is located at /usr/lib/wanrouter/doc/WANPIPE_CONFIG.txt\n"

	echo -e "\nNOTE: Any old wanpipe1.conf file will be saved with .old extension"
	echo -e "        (Ex. wanpipe1.conf will be saved as wanpipe1.conf.old)\n" 

	pause "\n\t!!! Wanpipe configuration files have been succesfully installed !!!\n"
	return 0
}

# ----------------------------------------------------------------------------
# Create meta-configuration file.
# ----------------------------------------------------------------------------
create_mataconf()
{
	# 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 

	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 directory.  These are:
#
#               ROUTER_BOOT=            Boot flag (YES/NO).
#               WANPIPE_CONF_DIR=       Directory of wanpipe config 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 'router start'
#                                       (ex: "wanpipe1 wanpipe2 wanpipe3...")
#
#                              Note:    Name of wanpipe devices correspond
#                                       to the configuration files in
#                                       /etc directory:
#                                         (ex. /etc/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=/etc"	>> $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

	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.
	[ -f $ROUTER_RC ] && . $ROUTER_RC
#	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
#	[ -f $X25API_CONF ] && rm -f $X25API_CONF

	#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
	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 $PROD_HOME/src directory\n"
	cd $PROD_HOME/src

	[ -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 "\t* Select N bellow if you wish to compile the $PROD_HOME/src"
		echo -e "\t  directory manually."
		echo -e "\t* Select Y bellow to symbolically link the '$INCLUDE' directory"
                echo -e "\t  to the default linux include directory and continue "
		echo -e "\t  with compilation (Recommended).\n" 
		getyn "  Would you like to use default /usr/src/linux/include/linux path ?" 			|| { return 1; }   
	        
		cd /usr/include
		ln -s ../src/linux/include/linux/ linux
		[ $? -eq 0 ]  || { 
			echo -e "\n\tCould not create a symbolic link to ";
			echo -e "\t/usr/src/linux/include/linux";
			echo -e "\tPlease contact Sangoma Technologies at: (905) 474-1990\n"
			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 c' from the $PROD_HOME directory to finish up";
		echo -e "\tthe WANPIPE Tools installation.\n";
		pause		
		return 0;
	}

	cd $PROD_HOME/src

	delete_old_tools;

	exec make | grep "Ok\." > /dev/null	
	if [ $? -eq 0 ]
	then
		echo -e "\n\t\tWANPIPE Tools Compilation OK"
		echo -e "\tWANPIPE Tools have been installed successfully\n"
	else
		echo -e "\n\t\t!!! WANPIPE Tools Compilation Failed !!!"
		echo -e "\n\tIf you are running 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 $PROD_HOME/src/bin/* /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

	pause
	return 0
}

delete_old_tools()
{
	local tools="wanconfig sdladump cpipemon fpipemon ppipemon"
	local tool

	for tool in $tools; do
		TOOL_EXE="/usr/sbin/$tool"
		[ -f "$TOOL_EXE" ] && rm -f $TOOL_EXE	
	done
}

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
}

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

PATH=/bin:/sbin:/usr/bin:/usr/sbin
KERNEL=`uname -r`
PROD=wanrouter
#X25API=x25api
PROD_VER=2.1.1
META_CONF=/etc/$PROD.rc
PROD_CONF=/etc/wanpipe1.conf
#X25API_CONF=/etc/x25api.conf
PROD_HOME=/usr/lib/$PROD
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
FIX=Fix_2.2.11
INCLUDE=/usr/include/linux

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
}

[ "$1" = "remove" ] && { remove; exit; }
[ "$1" = "c" ] && { compile_src; exit; }
if test $1
then
	echo -e "\nUSAGE:";
	echo -e "   ./Setup {optons}";
	echo -e "\n           <none>    : Install WANPIPE"
	echo -e "            remove   : Uninstall WANPIPE";
	echo -e "            c        : 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

