#!/bin/bash
# 20200727

function checkppp() {
    wvdialpid=`pidof wvdial`
    pppdpid=`pidof pppd`
    if [ "x$wvdialpid" == "x" -a "x$pppdpid" == "x" ]; then
	return 1
    else
	return 0
    fi
}

case "$1" in
	start-ppp)
	checkppp
	if [ $? == 0 ] ; then
		echo "PPP is already running"
		logger -t $0 "PPP is already running"
		exit 1
	fi
	echo "Starting PPP connection..."
	logger -t $0 "Starting PPP connection"
	/usr/bin/sudo /usr/bin/wvdial --config /root/.wvdial.conf >/home/terminal/atm_wvdial.log 2>&1 &
	sleep 1
	;;

	stop-ppp)
	echo "Stopping PPP connection..."
	logger -t $0 "Stopping PPP connection"
	/usr/bin/sudo /usr/bin/killall wvdial
	sleep 1
	/usr/bin/sudo /usr/bin/killall pppd
	# Wait for stop
	while checkppp ; do
	    sleep 1
	done
	sleep 3
	;;

	reboot)
	echo "Rebooting"
	logger -t $0 "Rebooting"
	/usr/bin/sudo /sbin/reboot
	;;

	start-vpn)
	ovpnpids=`ps ax | grep openvpn | grep bin`
	if [ "x$ovpnpids" != "x" ] ; then
		echo "openvpn is already running"
		logger -t $0 "openvpn is already running"
		exit 1
	fi
	echo "Starting openvpn"
	logger -t $0 "Starting openvpn"
	/usr/bin/sudo /etc/init.d/openvpn start
	;;

	stop-vpn)
	echo "Stopping openvpn"
	logger -t $0 "Stopping openvpn"
	/usr/bin/sudo /etc/init.d/openvpn stop
	sleep 1
	ovpnpids=`ps ax | grep openvpn | grep bin`
	if [ "x$ovpnpids" != "x" ] ; then
		/usr/bin/sudo /usr/bin/killall openvpn
	fi
	;;

	*)
        echo "Usage: $0 {start-ppp|stop-ppp|reboot|start-vpn|stop-vpn}"
        exit 1
        ;;
esac
