#!/bin/sh
#
# $Id: synce-serial-start.in,v 1.9 2005/07/08 19:04:42 twogood Exp $
#
# Script for starting a PPP connection for SynCE
#

THIS=`basename $0`

# include common stuff
. /usr/pkg/share/synce/synce-serial-common

exit_if_not_root

get_pid

if [ "${PID}" ]; then
	echo "
${THIS} detected that a SynCE serial connection was already 
started with PID ${PID}.

To be able to start a new connection, you may use synce-serial-abort to
force the already active connection to close.
" >&2
	exit 1
fi


#
# Prevent some support requests by asking the user to remove the usepeerdns
# option from the /etc/ppp/options file.
#

if cat ${PPP_OPTIONS} | grep -v '^[ 	]*#' | grep -q usepeerdns; then
	echo "
${THIS} encountered a problem with your ${PPP_OPTIONS} file:

The 'usepeerdns' option is not compatible with SynCE.  Please edit
${PPP_OPTIONS} and remove this option before running this script again.
" >&2

	exit 1
fi

#
# Check for the peer file to prevent some confusing error from pppd.
#

if [ ! -e ${PEER_FILE} ]; then
	echo "
${THIS} was unable to find the file ${PEER_FILE}:

Please run the synce-serial-config tool to create this file before running this
script again.
" >&2
	exit 1
fi

#
# Check for ppp_async kernel module
#

if [ "`uname -s`" = "Linux" ]; then
  export PATH=/sbin:/usr/sbin:$PATH
  if ! grep -q ppp /proc/devices; then
    if ! modprobe ppp_async; then
    echo "
${THIS} was unable to load the ppp_async kernel module:

Please add this module to your Linux kernel before running this script again.
" >&2
    exit 1
    fi
  fi
fi

#
# Check for file in /dev
# 
DEVICE=`awk '/^\/dev\// { print $1 }' ${PEER_FILE}`
if [ "$DEVICE" ]; then
  if [ !  -c "$DEVICE" ]; then
    echo "
Error!

${THIS} could not find the serial port $DEVICE.
Is your Windows CE device really connected?
" >&2
    exit 1
  fi
fi


#
# Check for suspected firewall
#

MD5=/usr/bin/md5sum
IPTABLES=/sbin/iptables
EMPTY_IPTABLES_MD5SUM="f2384cfbed4d4fb64061368c4128d7ea"

# Do we have md5 or md5sum?

if [ -x $MD5 ]; then

	# Do we have iptables?
	if [ -x $IPTABLES ]; then
		# Is iptables working?
		if $IPTABLES -L > /dev/null; then
			IPTABLES_MD5SUM=`$IPTABLES -L -n | $MD5 | sed 's/[ 	].*//'`
			if [ "$EMPTY_IPTABLES_MD5SUM" != "$IPTABLES_MD5SUM" ]; then
				echo "
Warning!

You have firewall rules that may prevent SynCE from working properly!
" >&2
			fi
		fi		
	fi

fi

#
# See if dccm is running
#

PGREP=`which pgrep`
if [ "$PGREP" ]; then
  $PGREP dccm >/dev/null || echo "
Warning!

${THIS} cannot find the dccm process.
Without dccm your PPP connection will soon terminate!
" >&2
fi

#
# Finally start pppd
#

${INFO} "Executing '${COMMAND}'"

if ${COMMAND}; then
	echo "
${THIS} is now waiting for your device to connect
"
	exit 0
else
	echo "
${THIS} was unable to start the PPP daemon!
" >&2
	# return the error code we got from pppd
	exit
fi

