#!/bin/sh
# Setup		WAN Router Installation/Removal Script.
#
# Copyright	(c) 1996-1997, 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.
# ----------------------------------------------------------------------------
# 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-1997, 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 'zImage')
	4) build modules with 'make modules'
	5) install modules with 'make modules_install'
	6) re-boot your system

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

	# 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
	}
	cd $PROD_HOME/patches
 
	# Check installed version.
	if [ -f $SOURCEDIR/net/router/patchlevel ]
	then
		OLD_VERSION=`cat $SOURCEDIR/net/router/patchlevel`
		parse_version $OLD_VERSION
		OLD_MAJ=$MAJVER
		OLD_MIN=$MINVER
		tmp=$SUBVER
		parse_version $PROD_VER

		[ "$OLD_MAJ" != "$MAJVER" -o "$OLD_MIN" != "$MINVER" ] && {
			error "Cannot upgrade from version $OLD_VERSION"
			getyn "\nWould you like to continue?"
			return
		}
		[ "$tmp" -ge "$SUBVER" ] && {
			error "Installed version $OLD_VERSION is the same or newer"
			getyn "\nWould you like to continue?"
			return
		}

		echo -e "\nUpgrading from version $OLD_VERSION ..."
		while	[ $tmp -lt $SUBVER ]; do
			tmp=`expr $tmp + 1`
			gzip -cd ${PROD}_upgrade-$MAJVER.$MINVER.$tmp.gz |\
			patch -usEN -p || {
				getyn "\nWould you like to continue?"
				return
			}
		done
	else
		gzip -cd $PROD.gz | patch -usEN -p || {
			getyn "\nWould you like to continue?"
			return
		}
	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

#	echo "Rebuilding source dependencies. Please wait..."
#	make dep || pause ""
	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 WAN driver documentation for more information.

ENDOFTEXT

	# Create meta-configuration file.
	[ -f $META_CONF ] || create_mataconf

	# Install sample router configuration file.
	[ -f $PROD_CONF ] || cp $PROD_HOME/samples/router.conf $PROD_CONF

	pause "Router configuration files has been succesfully installed."
	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 ]
	then	LOG_FILE=/var/adm/$PROD
	else	LOG_FILE=$PROD_HOME/$PROD.log
	fi

	# Select directory for the lock file.
	if	[ -d /var/lock ]
	then	LOCK_FILE=/var/lock/$PROD
	else	LOCK_FILE=$PROD_HOME/$PROD.lck
	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 directory.  These are:
#
#		ROUTER_BOOT=		Boot flag (YES/NO).
#		ROUTER_CONF=		Router configuration file.
#		ROUTER_LOG= 		Where to put start-up log file.
#		ROUTER_LOCK=		File used as a lock.
#		WAN_DRIVERS=		List of WAN drivers.
#
#		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 "ROUTER_CONF=$PROD_CONF"	>> $META_CONF
	echo "ROUTER_LOG=$LOG_FILE"	>> $META_CONF
	echo "ROUTER_LOCK=$LOCK_FILE"	>> $META_CONF
	echo "WAN_DRIVERS=\"\""		>> $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 start-up script?" || return 0

	# 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
	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
	ROUTER_CONF=${ROUTER_CONF:=$PROD_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 $ROUTER_CONF ] && rm -f $ROUTER_CONF

	# 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
}

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

PATH=/bin:/sbin:/usr/bin:/usr/sbin
KERNEL=`uname -r`
PROD=router
PROD_VER=2.0.1
META_CONF=/etc/$PROD.rc
PROD_CONF=/etc/$PROD.conf
PROD_HOME=/usr/lib/$PROD
PROD_INIT=/usr/sbin/$PROD
FILELIST=$PROD_HOME/Filelist
SOURCEDIR=/usr/src/linux
START_SCRIPT=S20$PROD
STOP_SCRIPT=K10$PROD

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; }
welcome || exit 0
prepare	|| exit 1
apply_patches || exit 1
install_init || exit 1
install_config || exit 1
goodbye

