#!/bin/sh
#
# Written by mr 2003/01/03
# single start and stop of one cipe-device not yet established
# Version 0.1
#
. /etc/rc.cfg

if [ "$2" != "" ]
then
    cipe_dev=$2
else
    cipe_dev="all"
fi

# get the dyn_dns and dyn_ip
eval dyn_dns='$DYNDNS_HOST_1'"."'$DYNDNS_DOMAIN_1'
eval dyn_ip=`ping -c 1 "$dyn_dns" | grep "bytes from" | cut -f4 -d" " | sed s/://g`

idx=1
while [ "$idx" -le "$CIPE_N" ]
do
	eval ptpaddr='$CIPE_'$idx'_REMOTE_INTERFACE_ADDR'
	eval ipaddr='$CIPE_'$idx'_LOCAL_INTERFACE_ADDR'
	eval ping_peer='$CIPE_'$idx'_REMOTE_ADDR'
	#eval ping_peer=`echo $peer | cut -f1 -d":"`

	my_cipe=`/sbin/ifconfig | grep "$ptpaddr"`		# is cipe for this peer running on my side?

	if [ "$idx" = "$cipe_dev" -o "$cipe_dev" = "all" ]
	then
		case "$1"
		in
		    start)					# start of cipe
		
				. /etc/ppp/ip-up.cipe		# /sbin/insmod cipcb cipe_debug=0 und pings
				/sbin/ciped-cb -o /etc/cipe/options-1
				. /etc/cipe/ip-up-1
				
				exit
		    
#				/sbin/insmod cipcb
#				/sbin/ciped-cb -o /etc/cipe/options-1
#				/sbin/ciped-cb -o /etc/cipe/options-2
#				/etc/ciperoute
#				exit
				
#				if [ "`lsmod | grep cipcb | grep -v grep`" = "" ]	
#				then					
#					/sbin/insmod cipcb		# start kernel module
#				fi
#		
#				if [ "$my_cipe" = "" ]
#				then 
#					/sbin/ciped-cb -o /etc/cipe/options-$idx
#					/etc/ciperoute -> Route muss extra gestartet werden!!
#				fi
				
		        ;;
		    stop)					# stop of cipe
		
				/usr/bin/killall -9 ciped-cb
				/sbin/ifconfig cipcb* down
				/sbin/rmmod cipcb
		
				exit
		        ;;
		    status)					# status
				echo -n "$idx $ping_peer "
				# is my cipe device enabled?:
				if [ "$my_cipe" != "" ]
				then 
					echo -n "my_cipe:$ipaddr "
				else
					echo -n "my_cipe:DOWN "
				fi
	
				# is own dyndns service working - (maybe it points on wrong destination...)?:	
				if [ "$dyn_ip" != "" ]
				then 
					echo -n "my_dyndns:$dyn_ip "
				else
					echo -n "my_dyndns:DOWN "
				fi				
				
				# ping on peer
				roundtrip_peer=`ping -c 1 $ping_peer | grep "bytes from" | cut -f7 -d" " | cut -f2 -d"="`
				if [ "$roundtrip_peer" != "" ]
				then 
					echo -n "ping_peer:$roundtrip_peer "
				else
					echo -n "ping_peer:DOWN "
				fi	

				# ping on peer cipe (only necessary, when own cipe is working)
				if [ "$my_cipe" != "" ]
				then
					roundtrip_ptpaddr=`ping -c 1 $ptpaddr | grep "bytes from" | cut -f7 -d" " | cut -f2 -d"="`
				fi
				if [ "$roundtrip_ptpaddr" != "" ]
				then 
					echo "ping_cipe:$roundtrip_ptpaddr"
				else
					echo "ping_cipe:DOWN"
				fi	

		        ;;
		    debug)					# full debug of the connection
				echo "$peer:"
				echo "kernel module"
				lsmod | grep cipcb | grep -v grep
				
		        
		        ;;
		    *)						# info
		        echo "usage: $0 (start|stop|status|debug) (<device number>|[all])" >&2;
		        exit 1
		        ;;
		esac
	fi
	idx=`/usr/bin/expr $idx + 1`
done
