#!/bin/bash
#***************************************************************
# WANCFG :  WANPIPE(tm) Configuration Utility
#
# Author :  Nenad Corbic <ncorbic@sangoma.com>
# Date   :  Jan 5, 2000
#
#=============================================================== 
# Copyright:    (c) 1999-2001 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 30. 2001 Nenad Corbic	Updated the options.ttyW file setup
#				to disable all pppd compression.
# May 12, 2001 Alex Feldman 	Added T1/E1 support (TE1).
# Mar 12, 2001	 		Added new interface support (redhat)
# Mar 13, 2000          	Added support for x25 protocol
# Jan 05, 2000   		Initial Version
#***************************************************************

#============================================================
# set_geometry 
#
#	Limits the geometry of the xterm window
#
#============================================================

#Limits the geometry of the xterm window
set_geometry () {
	# Some distributions export these with incorrect values
	# which can really screw up some ncurses programs.
	LINES=  COLUMNS=

	ROWS=${1:-24}  COLS=${2:-80} 

	# Just in case the nasty rlogin bug returns.
	#
	[ $ROWS = 0 ] && ROWS=24
	[ $COLS = 0 ] && COLS=80

	if [ $ROWS -lt 24 -o $COLS -lt 80 ]
	then
		echo -e "\n\007Your display is too small to run WANPIPE Config!"
		echo "It must be at least 24 lines by 80 columns."
		cleanup
		exit 0
	fi 

	ROWS=$((ROWS-4))  COLS=$((COLS-5))
}


#============================================================
# text_area
#
#	Used to printout the help textarea
#
#============================================================

function text_area () {

	local ROW=$1
	local COL=$2
	if [ -z "$ROW" ]; then
		ROW=20
	fi
	if [ -z "$COL" ]; then
		COL=60
	fi

	$DIALOG --backtitle "$backtitle" \
        	--textbox $TEMP $ROW $COL 

	rm -f $TEMP  
}

#============================================================
# menu_name
#
#
#
#============================================================

#Creates actual menu for lxdialog
#Uses linux version of dialg
function menu_name () {

	local ROW
	local COL

	ROW=${6:-20}  
	COL=${7:-50}

	echo "function Mycmd () {">Mycmd
	echo "$DIALOG --title '$1'\
			--backtitle \"$backtitle\" \\" >> Mycmd

	if [ $5 -eq 0 ]; then
		echo "		--menu '$4 $menuinstr_exit' \\" >> Mycmd
	else
		echo "		--menuback '$4 $menuinstr_back' \\" >> Mycmd
	fi
	echo "		$ROW $COL $3 '' \
			$2 " >> Mycmd
	echo "return \$?">> Mycmd
	echo "}">>Mycmd

	echo -n "."
	source ./Mycmd
	rm -f Mycmd
	Mycmd
	return $?
}

function menu_text () {

	local ROW
	local COL

	ROW=${5:-20}  
	COL=${6:-50}

	echo "function Mycmd () {">Mycmd
	echo "$DIALOG --title '$1'\
			--backtitle \"$backtitle\" \
			--menutext $TEMP \
			$ROW $COL $3 '' \
			$2 " >> Mycmd
	echo "return \$?">> Mycmd
	echo "}">>Mycmd

	echo -n "."
	source ./Mycmd
	rm -f Mycmd
	Mycmd
	return $?
}



#============================================================
# start_menu
#
#
#
#============================================================

#Initial menu, 
# Create or Edit Configuration file
start_menu () {

	local menu_options

	menu_options="'NEW'  'Create a new Configuration File' \
		      'EDIT' 'Edit existing Configuration File' 2> menu.tmp.$$"


	menu_instr="Please choose to Create or Edit Wanpipe configuration file. "
	menu_name "CONFIGURATION OPTIONS" "$menu_options" 2 "$menu_instr" "$EXIT" 
	retval=$?

	choice=`cat menu.tmp.$$`
	rm -f menu.tmp.$$

	case $retval in
		0)
			result "$choice" 
			return 0;
			;;
		1)
			return 1 
			;;

		2) 	start_menu_help
			start_menu
			;;

		255)	exit 0
			;;
	esac
}

#============================================================
# yesno 
#
#
#
#============================================================

yesno () {
	local ROW
	local COL

	ROW=${2:-10}  
	COL=${3:-40}

        ${DIALOG} --backtitle "$backtitle" --clear \
                  --yesno "$1" $ROW $COL  
  	case $? in
  	0)
		return 0;;
  	*)
		return 1
		;;
	esac       

}

text_yesno () {

	local ROW
	local COL

	ROW=${1:-10}  
	COL=${2:-40}

        ${DIALOG} --backtitle "$backtitle" --clear \
                  --textyesno $TEMP $ROW $COL  
	
	rc=$?
	rm -f $TEMP

	case $rc in
  	0)
		return 0;;
  	*)
		return 1;;
	esac      
}

#============================================================
# input_int 
#
#Gets an integer from the user
#
#============================================================

function input_int () {

	local int_input
	local retval
	
	$DIALOG --backtitle "$backtitle" --clear \
		--inputbox "$1" 10 50 "$2" 2> inputbox.tmp.$$

	retval=$?

	int_input=`cat inputbox.tmp.$$`
	rm -f inputbox.tmp.$$

	case $retval in
	  	0)
			if expr "$int_input" : '[0-9][0-9]*$' >/dev/null
                        then
				result "$int_input"
				return 
                        else
				yesno "You have choosen illegal number, would you like to try again?"
				if [ $? -eq 0 ]; then
					input_int "$1" "$2" "$3"
				fi
                        fi      
			return;;
		1)
			if [ ! -z "$3" ]; then
				$3 
				input_int "$1" "$2" "$3" 
			else
				return
			fi
			;;
	  	*)
			return;;
	esac       
}

#============================================================
# get_num_of_devices 
#
#	Gets the device number from the
#	use
#
#============================================================

get_num_of_devices () {

	local menu_options

	menu_options="'1' 'wanpipe1' \
		      '2' 'wanpipe2' \
		      '3' 'wanpipe3' \
		      '4' 'wanpipe4' \
		      '5' 'wanpipe5' \
		      '6' 'wanpipe6' \
		      '7' 'wanpipe7' \
		      '8' 'wanpipe8' \
		      '9' 'wanpipe9' \
		      '10' 'wanpipe10' \
		      '11' 'wanpipe11' \
		      '12' 'wanpipe12' \
		      '13' 'wanpipe13' \
		      '14' 'wanpipe14' \
		      '15' 'wanpipe15' \
		      '16' 'wanpipe16' 2> menu.tmp.$$"

	#menu_options="'1' 'wanpipe1' 2> menu.tmp.$$"


	if [ $EDIT_NEW_OPTION = NEW ]; then	
		menu_instr="	Please select a NEW Wan Device Name. \
					"
		menu_title="NEW WANPIPE CONFIGURATION"
	else
		menu_instr="Editing an existing WANPIPE configuration \
						\
                                Please select existing Wan Device for editing. \
									"
		menu_title="EDITING WANPIPE CONFIGURATION"
	fi
	
	menu_name "$menu_title" "$menu_options" 7 "$menu_instr" "$EXIT" 20 
	retval=$?

	choice=`cat menu.tmp.$$`
	rm -f menu.tmp.$$

	case $retval in
		0)
			DEVICE_NUM=$choice;
			if [ ! -f "$PROD_CONF/wanpipe$DEVICE_NUM.conf" ]; then
				if [ $EDIT_NEW_OPTION = EDIT ]; then
					warning "EDIT_NOT_EXIST"
					if [ $? -eq 0 ]; then
						#User wants to create 
						EDIT_NEW_OPTION=NEW
						return 0
					fi
				else
					return 0
				fi
			else
				if [ $EDIT_NEW_OPTION = NEW ]; then
					warning "NEW_EXIST"
					if [ $? -eq 0 ]; then
						#User wants to create 
						EDIT_NEW_OPTION=EDIT
					fi
				fi
				return 0
			fi	
			get_num_of_devices		
			;;
		2) 	echo "No Help Available at this point" > $TEMP
			text_area
			get_num_of_devices	
			;;

		*)	return 1
			;;
	esac
}

#============================================================
# create_menu
#
# 	Displays the Second Menu whith following options:
#   	Define Device, Define Interfaces, 
#   	Wan Device Setup, Interface Setup
#============================================================
create_menu () {

	local menu_options
	local intr_mess
	local dev_mess
	local te_mess
	local menu_size
	local prot_mess

	NUM_OF_INTER=${NUM_OF_INTER:-1}

	
	if [ ${#IF_NAME[@]} -eq 0 ]; then
		intr_mess="Undefined"
	else
		intr_mess="${#IF_NAME[@]} Defined"
	fi	

	dev_mess=${DEVICE_TYPE:-Undefined}
	# TE1 Set default value 
	DEVICE_TE1_TYPE=${DEVICE_TE1_TYPE:-NO}
	if [ $DEVICE_TE1_TYPE = YES ]; then
		dev_mess="T1/E1"
	fi
	te_mess=${MEDIA:-Undefined}


	if [ ${#INTR_STATUS[@]} -eq 0 ]; then
		intr_stat_mess="Undefined"
	else
		intr_stat_mess="${#INTR_STATUS[@]} Configured"
	fi

	if [ ${#IP_STATUS[@]} -eq 0 ]; then
		ip_mess="Undefined"
	else
		ip_mess="${#IP_STATUS[@]} Configured"
	fi

	case $PROTOCOL in
		WAN_FR)   prot_mess="Frame Relay";;
		WAN_PPP)  prot_mess="PPP";;
		WAN_CHDLC)prot_mess="Cisco HDLC";;
		WAN_X25) prot_mess="X25";;
		WAN_MULTPPP) prot_mess="MultiPort PPP";;	#New SyncPPP over RAW CHDLC
		WAN_TTYPPP)  prot_mess="TTY PPP";;
		WAN_BITSTRM) prot_mess="Bit Streaming";;
		WAN_EDU_KIT) prot_mess="Educational Kit";;
		WAN_BSC) prot_mess="BiSync";;
		*) prot_mess="Undefined";;
	esac 
	
	echo "'select_protocol'   'Wan Protocol Definition------> $prot_mess' \\" > $TEMP
	menu_size=1

	if [ ! -z "$PROTOCOL" ]; then
		echo "'again' 	       ' ' \\" >> $TEMP
		echo "'device_setup'     'Hardware Setup --------------> $dev_mess' \\" >> $TEMP
		menu_size=3
 	       	# TE1 For T1/E1 board, add new hardware configuration menu
       	 	if [ $DEVICE_TE1_TYPE = YES ]; then
			echo "'again' 	       ' ' \\" >> $TEMP
			echo "'device_te_setup'     'T1/E1 Hardware Setup --------> $te_mess' \\" >> $TEMP
			menu_size=5
        	fi

		if [ $PROTOCOL != WAN_TTYPPP ] && [ $PROTOCOL != WAN_EDU_KIT ]; then
			echo "'again' 	       ' ' \\" >> $TEMP	
			echo "'define_interface' 'Network Interface Setup -----> $intr_mess' \\">> $TEMP
			menu_size=$((menu_size+2))
		fi
	fi
	echo " 2> menu.tmp.$$" >> $TEMP

	menu_options=`cat $TEMP` 
	rm -f $TEMP


	menu_instr="New Configuration for Wan Device: 'wanpipe$DEVICE_NUM' \
					"
	menu_name "MAIN WANPIPE CONFIGURATION" "$menu_options" "$menu_size" "$menu_instr" "$EXIT" 20 
	retval=$?

	choice=`cat menu.tmp.$$`
	rm -f menu.tmp.$$

	case $retval in
		0)	case $choice in
			again)
				return 0
				;;
			*)
				$choice
				;;
			esac
			return 0
			;;
		2)	choice=${choice%\"*\"}
			choice=${choice// /} 
			create_menu_help $choice
			create_menu	
			;;
		*)
			return 1
			;;
	esac

}

#--------------------------- DEVICE AREA OPTIONS ---------------------

#============================================================
# select_protocol
#
#	Option to select a desired protocol
#
#============================================================


#Gets Protocol from the user
select_protocol () {
	
	local choice
	local retval
	local menu_optonis
	local old_prot

	old_prot=${PROTOCOL:-UNDEF}

	menu_options="'WAN_FR'    'Frame Relay Protocol' \
		      'WAN_CHDLC' 'Cisco HDLC Protocol' \
		      'WAN_X25'   'X25 Protocol' \
	              'WAN_PPP'   'Point to Point Protocol' \
		      'WAN_MULTPPP' 'MultiPort PPP' \
		      'WAN_TTYPPP' 'Sync/Async TTY PPP' \
		      'WAN_BITSTRM' 'Bit Streaming Protocol' \
		      'WAN_BSC' 'BiSync API Protocol' \
		      'WAN_EDU_KIT' 'Educational Kit Protocol' 2> menu.tmp.$$"

	menu_instr="	Please select a WAN Protocol \
							"
	menu_name "PROTOCOL DEFINITION" "$menu_options" 9 "$menu_instr" "$BACK"
	retval=$?

	choice=`cat menu.tmp.$$`
	rm -f menu.tmp.$$

	case $retval in
		0) 	if [ $old_prot != $choice -a $old_prot != UNDEF ]; then
				warning "PROTOCOL_CHANGE"
				if [ $? -eq 0 ]; then
					unset IF_NAME
					unset DEVICE_TYPE
					unset INTR_STATUS
					unset PROT_STATUS
					unset IP_STATUS
					unset NUM_OF_INTER
					unset DLCI_NUM
					# TE1 Initialize T1/E1 flag.
					unset DEVICE_TE1_TYPE
					
					PROTOCOL=$choice
					if [ $PROTOCOL = WAN_X25 ]; then
						STATION=DCE	
					elif [ $PROTOCOL = WAN_FR ]; then
						STATION=CPE
					fi

				fi
			else
				PROTOCOL=$choice
			fi	
			case $choice in
			WAN_FR) 
			    backtitle="WANPIPE Configuration Utility: Frame Relay Setup"
 				;;
			WAN_CHDLC) 
			    backtitle="WANPIPE Configuration Utility: CHDLC Setup"
				;;
			WAN_PPP)
			    backtitle="WANPIPE Configuration Utility: PPP Setup" 	
				;;
			WAN_X25)
			    backtitle="WANPIPE Configuration Utility: X25 Setup" 	
				;;
			WAN_MULTPPP)
			     backtitle="WANPIPE Configuration Utility: SyncPPP Setup" 	
				;;
			WAN_TTYPPP)
			     backtitle="WANPIPE Configuration Utility: Sync/Async TTY PPP Setup" 	
				;;
			WAN_EDU_KIT)
			     backtitle="WANPIPE Configuration Utility: Educational Kit Setup"	 
				;;
			WAN_BSC)
			     backtitle="WANPIPE Configuration Utility: BiSync Setup"	 
				;;
			esac
			return 0 
			;;
		2)	choice=${choice%\"*\"}
			choice=${choice// /} 
			select_protocol_help $choice
			select_protocol
			;;
		*)
			return 1
			;;
	esac
}



#============================================================
# get_string
#
#	Accepts sring from the user. 
#	Check IP Addresses.
#	Dispays default values.
#
#============================================================


function get_string () {

	local is_ip=${3:-BAD_STRING}

	$DIALOG --backtitle "$backtitle" --clear \
		--inputbox "$1" 10 50 "$2" 2> inputbox.tmp.$$

	retval=$?

	input=`cat inputbox.tmp.$$`
	rm -f inputbox.tmp.$$

	case $retval in
	  	0)
			if [ -z "$input" ]; then
				result "$2" 
				return 0	
			fi

			if expr "$input" : '[0-9a-zA-Z/_\.\*-]*$' >/dev/null
                        then
				if [ $is_ip = IP_ADDR ]; then
					expr "$input" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' > /dev/null
					if [ $? -eq 0 ];
					then
						result "$input"
						return 0
					fi
				else
                               		result "$input"
					return 0
				fi
                       	fi 

			warning "$is_ip"
			if [ $? -ne 0 ]; then
				result "$2"
				return 1
			fi
			get_string "$1" "$2" "$3"
			;;
	  	1) 	result "$2"	
			return 1
			;;
	  	255) 	result "$2"
			return 1
			;;
	esac       

}

#============================================================
# get_integer 
#
# 	Accepts integer value from the user, it also
#	check for correct entry and displays default value.
#	Furthermore, help is also supported.
#
#============================================================

function get_integer () {

	local min="$3"
	local max="$4"	
	local int_ret

	while true
	do
		input_int "$1" "$2" "$5"  
		int_ret=$($GET_RC)

		if [ $int_ret -ge 0 ]; then

			if [ $max -eq 0  ]; then
				result $int_ret
				return
			fi

			if [ $int_ret -gt $max -o $int_ret -lt $min ]; then
				yesno "Your selection is outside specified range: $min to $max.  Would you like to try again?"
				if [ $? -eq 1 ]; then
					result $2 
				 	return
				fi
			else	
				result $int_ret
				return  
			fi
		fi
	done	
}

#-------------------------- INTERFACE AREA --------------------------------

function auto_intr_cfg_menu ()
{

		menu_options="'manual'               'Manual Interface Setup' \
			      'auto_intr_config'     'Automatic Interface Setup' 2> menu.tmp.$$"

		menu_instr="	Please select an interface configuration option \
								"
		menu_name "INTERFACE CONFIG OPTIONS" "$menu_options" 2 "$menu_instr" "$BACK"
		rc=$?

		choice=`cat menu.tmp.$$`
		rm -f menu.tmp.$$

		case $rc in
			0)
				if [ $choice != manual ]; then
					AUTO_INTR_CFG=YES
					$choice 
					return
				else
					AUTO_INTR_CFG=NO
				fi
			;;
			2)
				create_menu_help $choice
				auto_intr_cfg_menu
				#help
				;;
			3) 	return
				;;
		esac
}



#============================================================
# define_interface
#
# 	Displays the Interface definition main menu
# 	It loops for number of interfaces to be defined
#
#============================================================

define_interface () {

	local ret1
	local if_num
	local intr_mess
	local menu_options
	local rc
	local write

	NUM_OF_INTER=${NUM_OF_INTER:-1}

	if [ $PROTOCOL = WAN_FR ]; then
		get_integer "Please specify the number of DLCIs supported on this Frame Relay connection. " "$NUM_OF_INTER" "1" "100" "interface_menu_help num_of_dlci" 
		NUM_OF_INTER=$($GET_RC)

	elif [ $PROTOCOL = WAN_X25 ]; then
		get_integer "Please specify the number of LCN's supported on the X25 connection. " "$NUM_OF_INTER" "1" "255" "interface_menu_help num_of_lcn"
		NUM_OF_INTER=$($GET_RC)
	else
		NUM_OF_INTER=1
	fi


	if [ $PROTOCOL = WAN_FR ] || [ $PROTOCOL = WAN_X25 ]; then
		if [ $NUM_OF_INTER -gt 1 ]; then
			auto_intr_cfg_menu
		fi
	fi

	while true 
	do
		if_num=0
		while [ $if_num -ne $NUM_OF_INTER ];
		do
			if_num=$((if_num+1))
			if [ -z "${IF_NAME[$if_num]}" ]; then
				intr_mess="Undefined"
			else
				intr_mess=${IF_NAME[$if_num]}
			fi	
			echo "'$if_num'   'Interface $if_num -----> $intr_mess' \\" >> $TEMP
		done
		echo " 2> menu.tmp.$$" >> $TEMP

		menu_options=`cat $TEMP`
		rm -f $TEMP 2> /dev/null

		interface_num_menu "INTERFACE DEFINITION" "$menu_options" 0	
		rc=$?
		if [ $rc -ne 0 ]; then
			break
		fi
	done

}

#============================================================
# interface_num_menu
#
#
#
#============================================================


interface_num_menu () {

	local choice



	menu_instr="	MAIN NETWORK INTERFACE CONFIGURATION \
				"

	if [ $NUM_OF_INTER -gt 10 ]; then
		menu_name "$1" "$2" 10 "$menu_instr" "$BACK"
		retval=$?
	else
		menu_name "$1" "$2" $NUM_OF_INTER "$menu_instr" "$BACK"
		retval=$?
	fi

	choice=`cat menu.tmp.$$`
	rm -f menu.tmp.$$

	case $retval in
		0)	interface_num "$choice" "$3"
			return 0 
			;;
		1) 	
			return 1
			;;
		2)   	interface_num_menu_help "$3"
			interface_num_menu "$1" "$2" "$3"				
			;;
		255) 	
			return 1
			;;
	esac
}

#============================================================
# interface_num
#
#	Repeats the interface_num menu until the user
#	selects back button. 
#
#============================================================


interface_num () {

	local if_num=$1
	local opt=$2
	local ret1

	while true
	do
		interface_menu "$if_num" 
		ret1=$?
		if [ $ret1 -eq 1 ]; then
			break
		fi
	done
	INTR_STATUS[$if_num]=setup
}

#============================================================
# interface_setup
#
#	Prints out all network interfaces, from where
#       the user has the choice to configure each one.
#============================================================


interface_setup () {

	local ret1
	local if_num
	local rc

	while true 
	do
		if_num=0
		while [ $if_num -ne $NUM_OF_INTER ];
		do
			if_num=$((if_num+1))
			if [ -z "${INTR_STATUS[$if_num]}" ]; then
				intr_mess="Unconfigured"
			else
				intr_mess="Configured"
			fi

			echo "'$if_num'   'Interface: ${IF_NAME[$if_num]} -----> $intr_mess' \\" >> $TEMP
		done
		echo " 2> menu.tmp.$$" >> $TEMP

		menu_options=`cat $TEMP`
		rm -f $TEMP 2> /dev/null

		interface_num_menu "INTERFACE/PROTOCOL SETUP" "$menu_options" 1	
		rc=$?
		if [ $rc -ne 0 ]; then
	 		break	
		fi
	done
}


#============================================================
# ip_setup
#
#	This function repeats the ip_setup_menu until
#  	the user selects back.
#
#============================================================

ip_setup () {

	local ret1
	local if_num="$1"
	local rc

	while true
	do
		ip_setup_menu $if_num
		rc=$?
		if [ $rc -ne 0 ]; then
	 		break	
		fi
	done
	IP_STATUS[$if_num]="Setup Done"

}

#============================================================
# prot_inter_setup 
#
# 	This function repeates the interface/protocol setup
#	menu for all the protocols untill the user exits 
#	using the back button or ESC.
#
#============================================================

prot_inter_setup () {
	
	local ret1
	local if_num="$1"
	local rc

	while true
	do
		case $PROTOCOL in	
		WAN_FR) 
			fr_interface_setup $if_num
			rc=$?
			;;
		WAN_MULTPPP)
			chdlc_interface_setup $if_num
			rc=$?
			;;
		WAN_CHDLC) 
			chdlc_interface_setup $if_num
			rc=$?
			;;
		WAN_TTYPPP)
			chdlc_interface_setup $if_num
			rc=$?
			;;
		WAN_PPP) 
			ppp_interface_setup $if_num
			rc=$?
			;;
		WAN_X25)
			x25_interface_setup $if_num
			rc=$?
			;;
		esac
		if [ $rc -ne 0 ]; then
	 		break	
		fi
	done
	PROT_STATUS[$if_num]="Setup Done"
}

#-------------- DEVICE SETUP FUNCTIONS --------------------------------
#============================================================
# device_setup
#
#	Hardware setup function.  This function repeats the
#       hardware menu untill the user exits using the back
#       button.
#============================================================


device_setup () {

	local ret1

	device_init
	
	while true
	do
		gen_device_setup 
		ret1=$?
		if [ $ret1 -eq 1 ]; then
			break
		fi
	done
}

#============================================================
# device_te_setup
#
#	Hardware T1/E1 setup function.  This function repeats
#       the hardware menu untill the user exits using the back
#       button.
#============================================================
device_te_setup () {

	local ret1

	device_te_init
	
	while true
	do
		gen_device_te_setup 
		ret1=$?
		if [ $ret1 -eq 1 ]; then
			break
		fi
	done
}

#============================================================
# result
#
#	Write a return code into a file.  We use this
#	since bash2 can only return a number from 0 to 255. 
#
#============================================================


function result () {
	echo "$1" > "$RC"
}

#============================================================
# cleanup  
#
#	Remove any temporary files during the session
#
#============================================================


function cleanup () {

	[ -f $DEF_DEVICE ] && rm -f $DEF_DEVICE 2> /dev/null
	[ -f $DEF_INTERFACE ] && rm -f $DEF_INTERFACE 2> /dev/null
	[ -f $WAN_DEVICE ] && rm -f $WAN_DEVICE 2> /dev/null
	[ -f $INTR_SETUP ] && rm -f $INTR_SETUP 2> /dev/null	
	[ -f $RC ] && rm -f $RC 2> /dev/null
	#clear
}

#============================================================
# check_setup  
#
#  	Check that all libraries exit as well as 
#       /etc/wanrouter.rc.  
#       Wanpipe Package must be installed before
#       proceeding.
#============================================================


function check_setup () {

	local ver
	local test=$1

if [ $test -eq 1 ]; then

	ver=`echo $BASH_VERSION`
	ver=${ver%%\.*} 
	if [ $ver -lt 2 ]; then
		cat <<EOM

	BASH VERSION ERROR

	This program can only run with
bash version greater than 2. Please read
the wancfg readme file on how to upgrade
your bash shell.	
	
EOM
		exit 1
	fi

	if [ ! -f "$PROD_HOME/wanrouter.rc" ]; then
		cat << EOM

	BAD CONFIGURATION - FILE MISSING

	/etc/wanrouter.rc file could not 
be found. Please make sure that the wanpipe
pacakge has been correctly installed before
proceeding to configure a Sangoma device.

EOM
		exit 1
	fi

else

	if [ ! -f "$WANCFG_LIB/lib.sh" ]; then
		cat <<EOM 

	BAD CONFIGURATION - LIBRARY MISSING

Library lib.sh cannot be found in $WANCFG_LIB/lib.sh directory.

Please make sure that the wanpipe
pacakge has been correctly installed before
proceeding to configure a Sangoma device.

EOM
		exit 1
	fi

	if [ ! -f "$WANCFG_LIB/fr_lib.sh" ]; then
		cat <<EOM 

	BAD CONFIGURATION - LIBRARY MISSING

Library fr_lib.sh cannot be found in lib/ directory.

Please make sure that the wanpipe
pacakge has been correctly installed before
proceeding to configure a Sangoma device.

EOM
		exit 1
	fi

	if [ ! -f "$WANCFG_LIB/chdlc_lib.sh" ]; then
		cat <<EOM 

	BAD CONFIGURATION - LIBRARY MISSING

Library chdlc_lib.sh cannot be found in lib/ directory.

Please make sure that the wanpipe
pacakge has been correctly installed before
proceeding to configure a Sangoma device.

EOM
		exit 1
	fi

	if [ ! -f "$WANCFG_LIB/ppp_lib.sh" ]; then
		cat <<EOM 

	BAD CONFIGURATION - LIBRARY MISSING

Library ppp_lib.sh cannot be found in lib/ directory.

Please make sure that the wanpipe
pacakge has been correctly installed before
proceeding to configure a Sangoma device.

EOM
		exit 1
	fi

	if [ ! -f "$WANCFG_LIB/help.sh" ]; then
		cat <<EOM 

	BAD CONFIGURATION - LIBRARY MISSING

Library help.sh cannot be found in lib/ directory.

Please make sure that the wanpipe
pacakge has been correctly installed before
proceeding to configure a Sangoma device.

EOM
		exit 1
	fi
fi

}

init_pppd_scripts ()
{

	
	MULTILINK=NO
	MULTILINK_MODE=SLAVE
	
	eval "uname -r | grep 2.4 > /dev/null"
	if [ $? -eq 0 ]; then
		warning "MULTILINK_OPT"
		if [ $? -eq 0 ]; then
			MULTILINK=YES

			warning "MULTILINK_MASTER"
			if [ $? -eq 0 ]; then
				MULTILINK_MODE=MASTER
			fi
		fi
	fi

	if [ $TTY_MODE = Sync ]; then

	PPPD_OPTION="
# ---------------------------------------------
# PPPD Daemon SYNC configuration file
# ---------------------------------------------
# options.ttyWP$TTY_MINOR
#
#  - PPPD daemon must bind to device /dev/ttyWP$TTY_MINOR
#  - The /dev/ttyWP$TTY_MINOR is binded to wanpipe$DEVICE_NUM
#
# Created automatically by /usr/sbin/wancfg
# Date: `date`
#
asyncmap 0

debug		#PPPD will output connection information

nodetach	#Do not detach into background

defaultroute	#This interface will be a default gateway.

nodeflate	#Do not use compression
nobsdcomp	#Do not use bsd compression
noccp		#Disable CCP (Compression Control Protocol)
noaccomp	#Disable  Address/Control compression
nopcomp		#Disable  protocol  field compres.
novj		#Disable Van Jacobson TCP/IP header compres.
novjccomp	#Disable the connection-ID compression
nopredictor1	#Do not accept or agree to Predictor-1 compres.


# Read pppd(8) for more information.
# Read /usr/local/wanrouter/PPP-HOWTO for more info.
"

	PPPD_CALL="
#------------------------------------------------
# PPPD Call SYNC Script
#------------------------------------------------
# This call script will call /etc/ppp/options.ttyWP$TTY_MINOR
# to setup the PPPD dameon.
#
# It will start PPPD SYNC protocol.
#
# Created automatically by /usr/local/wanrouter/wancfg
# Date: `date`
#
ttyWP$TTY_MINOR		#Bind to WANPIPE device wanpipe$DEVICE_NUM
sync		#Connect in sync mode
lcp-echo-failure 0	#No link verification messages
"

	if [ $MULTILINK = YES ]; then
		PPPD_CALL=$PPPD_CALL"
multilink	#Enable Multilink Protocol
"

		if [ $MULTILINK_MODE = SLAVE ]; then
			PPPD_CALL=$PPPD_CALL"
noip 		#No IP addresses for a slave
"
		fi

	fi

	if [ $MULTILINK = NO ] || [ $MULTILINK_MODE = MASTER ]; then

		get_string "Please specify the Local IP Address" "" "IP_ADDR" 
		L_IP=$($GET_RC)

		get_string "Please specify the Point-to-Point IP Address" "" "IP_ADDR" 
		R_IP=$($GET_RC)

		PPPD_CALL=$PPPD_CALL"
$L_IP:$R_IP	#Local and remote IP addresses
			#STATIC IP mode.
"
	fi

else

	PPPD_OPTION="
# ---------------------------------------------
# PPPD Daemon ASYNC configuration file
# ---------------------------------------------
# options.ttyWP$TTY_MINOR
#
#  - PPPD daemon must bind to device /dev/ttyWP$TTY_MINOR
#  - The /dev/ttyWP$TTY_MINOR is binded to wanpipe$DEVICE_NUM
#
# Created automatically by /usr/local/wanrouter/wancfg
# Date: `date`
#
asyncmap 0

modem		#Interface to a modem

debug		#PPPD will output connection information

crtscts		#Enable hardware flow control

noipdefault	#Enable dynamice IP addressing
	        #Obtaint Local and Remote IP addresses from
		#peer.

-detach		#Do not detach into background

defaultroute	#This interface will be a default gateway.

#nodeflate	#Do not use compression
#nobsdcomp	#Do not use bsd compression
#noccp		#Disable CCP (Compression Control Protocol)
#noaccomp	#Disable  Address/Control compression
#nopcomp		#Disable  protocol  field compres.
#novj		#Disable Van Jacobson TCP/IP header compres.
#novjccomp	#Disable the connection-ID compression
#nopredictor1	#Do not accept or agree to Predictor-1 compres.


persist		#If the link goes down, keep retrying to connect 



# Read pppd(8) for more information.
# Read /usr/local/wanrouter/PPP-HOWTO for more info.
"

	get_integer "Please specify the Baud Rate in bps" "38400" "64" "4096000" "device_setup_help get_baudrate"
	BAUDRATE=$($GET_RC)

	PPPD_CALL="
#------------------------------------------------
# PPPD Call ASYNC Script
#------------------------------------------------
# This call script will call /etc/ppp/options.ttyWP$TTY_MINOR
# to setup the PPPD dameon.
#
# It will start PPPD ASYNC protocol.
#
# Created automatically by /usr/local/wanrouter/wancfg
# Date: `date`
#
ttyWP$TTY_MINOR		#Bind to WANPIPE device wanpipe$DEVICE_NUM
$BAUDRATE		#Baud rate of the PPP link
connect '/etc/ppp/redialer'
"

	if [ $MULTILINK = YES ]; then
		PPPD_CALL=$PPPD_CALL"
multilink	#Enable Multilink Protocol
"

		if [ $MULTILINK_MODE = SLAVE ]; then
			PPPD_CALL=$PPPD_CALL"
noip 		#No IP addresses for a slave
"
		fi

	fi
fi

}



#============================================================
# VARIABLE DEFINITION 
#============================================================

WAN_CONF=wanpipe
RC=/etc/wanpipe/return_code
GET_RC="cat $RC"
TEMP=temp.$$
PROD_HOME=/etc/wanpipe
EXIT=0
BACK=1
LINUX_DISTR=unknown

menuinstr_exit="------------------------------------------ \
Use arrows to navigate through the options. \
Press <Enter> to select highlighted opt. \
Press <Exit> to exit Wanpipe configuration. \
Press <ESC> to go back, <Help> for help."

menuinstr_back="------------------------------------------ \
Use arrows to navigate through the options. \
Press <Enter> to select highlighted opt. \
Press <Back> to return to previous menu. \
Press <ESC> to go back, <Help> for help."

backtitle="WANPIPE Configuration Utility"


check_setup 1

#Load the library files
source $PROD_HOME/wanrouter.rc

check_setup 2

source $WANCFG_LIB/lib.sh
source $WANCFG_LIB/fr_lib.sh
source $WANCFG_LIB/ppp_lib.sh
source $WANCFG_LIB/chdlc_lib.sh
source $WANCFG_LIB/help.sh
source $WANCFG_LIB/x25_lib.sh

PROD_CONF=$WANPIPE_CONF_DIR
INTERFACE_DIR=$WANPIPE_INTR_DIR
NEW_IF=""

if [ $NEW_IF_TYPE = YES ]; then
	NEW_IF="ifcfg-"
fi

set_geometry `stty size 2>/dev/null`

DIALOG=${DIALOG=/usr/sbin/wanpipe_lxdialog}

if [ ! -f "$DIALOG" ]; then
	cat <<EOM

	!!! WANPIPE CONFIGURATOR FAILED !!!

Error:
------
	Wanpipe Configurator uses the 
lxdialog executable. This file cannot be found
make sure you run 'make' in current directory
before you proceed.

EOM
	exit 1
fi

PPPCONFIG=/usr/sbin/wp_pppconfig

#For now debian doesnt support pointopoint IP address
#thus disable it.
#eval "grep \"Debian\" -i /etc/issue > /dev/null"
#if [ $? -eq 0 ]; then 
#	LINUX_DISTR=debian	
#fi
#eval "grep \"Red *Hat\" -i /etc/issue > /dev/null"
#if [ $? -eq 0 ]; then
#	LINUX_DISTR=redhat	
#fi
#eval "grep \"Mandrake\" -i /etc/issue > /dev/null"
#if [ $? -eq 0 ]; then
#	LINUX_DISTR=redhat	
#fi

#============================================================
# MAIN PROGRAM 
#
#
#
#============================================================

#Initial menu

start_menu 
if [ $? -ne 0 ]; then
	cleanup
	exit 0
fi
EDIT_NEW_OPTION=$($GET_RC)

get_num_of_devices
if [ $? -ne 0 ]; then
	cleanup
	exit 0
fi

if [ "$EDIT_NEW_OPTION" = EDIT ]; then
	parse_config_file
fi

while true;
do
	while true;
	do
		create_menu
		gret=$?
		if [ $gret -ne 0 ]; then
			break
		fi
	done

	warning "ARE_YOU_SURE"
	if [ $? -eq 0 ]; then
		warning "SAVE_CONFIG"
		if [ $? -eq 1 ]; then
			break
		fi
		check_config
		if [ $? -eq 1 ]; then
			continue
		fi
		save_configuration
		#This is not an error, I am just using
                #it to print out the message 
		error "SAVE_OK"
	
		if [ $PROTOCOL = WAN_TTYPPP ]; then
		
			if [ ! -e "/dev/ttyWP$TTY_MINOR" ]; then
				warning "CREATE_TTYDEV"
				if [ $? -eq 0 ]; then
					eval "mknod -m 666 /dev/ttyWP$TTY_MINOR c 240 $TTY_MINOR 2> /dev/null"
					if [ $? -eq 0 ]; then 
						error "CREATE_TTYOK"
					else	
						error "CREATE_TTYFAIL"
					fi
				fi
			fi

			warning "CREATE_PPPDOPT"
			if [ $? -eq 0 ]; then
				if [ -f "/etc/ppp/options.ttyWP$TTY_MINOR" ]; then
					mv /etc/ppp/options.ttyWP$TTY_MINOR /etc/ppp/options.ttyWP$TTY_MINOR.old
				fi

				if [ "$TTY_MODE" = Sync ]; then
					init_pppd_scripts
					echo "$PPPD_OPTION" > /etc/ppp/options.ttyWP$TTY_MINOR
					echo "$PPPD_CALL"   > /etc/ppp/peers/isp_wanpipe$DEVICE_NUM
				else
					eval "$PPPCONFIG --ttyport /dev/ttyWP$TTY_MINOR --provider isp_wanpipe$DEVICE_NUM"
				fi

				error "CREATE_PPPDOK"
			fi
		fi
		
		break
	fi	
done

cleanup
exit 0
