#This script if for moxa hc25 multiplexer

#WARNING: Only setup module_num=2 when you has 2 epm3337 module
module_num=1

#-----------------------------------------------------------------------
#Module1
mux_port0='/dev/ttyACM0'
pts_port0='pts\/0'

#Module2
if [ $module_num -eq 2 ]; then 
mux_port1='/dev/ttyACM1'
pts_port1='pts\/3'
fi

#arg: $1:mux_port 
start_mux() {
	mux_pid=`ps aux | grep "[m]oxa_hc25_mux.\+$1" | awk '{print $2}'`
	if [ ! -z "$mux_pid" ] ; then
		echo WARNING: moxa_hc25_mux $1 is running, stop it first
	else
		moxa_hc25_mux  $1 &
		sleep 3
	fi
}
#arg: $1:mux_port $2:pts_port
stop_pppd_and_mux() {
	
	ppp_pid=`ps aux | grep "$2.\+pppd" | awk '{print $2}'`
	if [ ! -z "$ppp_pid" ] ; then
		echo "pppd $ppp_pid is still running, try to close it"
		kill $ppp_pid
		sleep 10
	fi
	mux_pid=`ps aux | grep "[m]oxa_hc25_mux.\+$1" | awk '{print $2}'`
	if [ ! -z "$mux_pid" ] ; then
		kill $mux_pid
		echo "Waiting moxa_hc25_mux $1 finish..."
		sleep 5
	fi
}


case "$1" in
start)	echo "Starting moxa hc25 multiplexer..." 
	start_mux  $mux_port0 

	if [ $module_num -eq 2 ]; then 
		start_mux  $mux_port1
	fi

	;;
stop) 	echo "Stopping moxa hc25 multiplexer..." 
	stop_pppd_and_mux $mux_port0 $pts_port0

	if [ $module_num -eq 2 ]; then 
		stop_pppd_and_mux $mux_port1 $pts_port1
	fi

	;;
*)	echo "Usage: /etc/init.d/$0 [start|stop]"
        ;;
esac
exit 0
