#!/bin/bash
### BEGIN INIT INFO
# Provides:          pppd-daemon
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts pppd-daemon.
### END INIT INFO

# peerName=$(wget -qO- 0.0.0.0:12800/admin/configure/value?key=ppp.name | grep -o '"[^"]*"' | sed 's/"//g' | tail -1)
DEAMON_NAME=pppd-${peerName}

PIDFILE=/var/run/$DEAMON_NAME.pid

#. /etc/init.d/functions

function running() {
  if [ -f $PIDFILE ]; then
    DPID=$(cat $PIDFILE)
    # lets check if the process is still running
    if ps -p $DPID 2>&1; then
      return 1
    else
      rm $PIDFILE
      return 0
    fi
  else
    return 0
  fi
  return 0
}

function start() {
  echo "Starting : $DEAMON_NAME"
  running
  if [[ $? != 0 ]]; then
    echo " already started"
    return
  fi
  if [ -e $PIDFILE ]; then
    rm $PIDFILE 2>&1
  fi
  # setAutoBaud
  touch $PIDFILE
  if [[ ! -f /var/log/debug ]]; then
    touch /var/log/debug
  fi
  # pppd call ${peerName} nodetach > /dev/null 2>&1 &
  pppd debug call ${peerName} 2>&1 &
  sleep 1
  # echo $! > $PIDFILE
  # Explicitly get the PID of the pppd daemon. Using $! would return the PID of this script being executed.
  callPID=$(ps aux | grep "pppd debug call" | grep -v grep | awk '{print $2}')
  echo "callPID: $callPID"
  echo $callPID > $PIDFILE
  # chatPID tailing breaks since chat is not called not active.
  # chatPID=$(ps aux | grep "/etc/ppp/chat" | grep -v grep | awk '{print $2}')
  # echo "chatPID: $chatPID"
  # echo "Waiting for /etc/ppp/chat PID:$chatPID to finish..."
	# tail --pid="$chatPID" -f /dev/null
  echo "$DEAMON_NAME Started"
  return
}

function stop() {
  echo "Shutting down : $DEAMON_NAME"
  killall -s 15 pppd
  killall chat
  sleep 2
  killall pppd
  killall chat
  sleep 1
  running
  if [[ $? == 0 ]]; then
    killall -9 pppd
    killall -9 chat
    echo " already stopped"
    return
  fi
  DPID=$(cat $PIDFILE)
  echo "killing $DPID"
  kill $DPID
  sleep 5
  running
  if [[ $? != 0 ]]; then
    kill $DPID
    sleep 5
  fi
  running
  if [[ $? != 0 ]]; then
    kill $DPID
    sleep 5
  fi
  running
  if [[ $? != 0 ]]; then
    echo "still running try to hard kill the proces"
    kill -9 $DPID
    sleep 2
    running
    if [[ $? != 0 ]]; then
      echo "ERROR: still running could not hard kill the process"
      killall -9 pppd
      killall -9 chat
      exit 2
    fi
  fi
  killall -9 pppd
  killall -9 chat
  rm $PIDFILE
  return
}

case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  stop
  start
  ;;
status)
  running
  if [[ $? == 0 ]]; then
    echo "$DEAMON_NAME is not running"
  else
    echo "$DEAMON_NAME is running"
  fi
  ;;
running)
  running
  ;;
*)
  echo "Usage:  {start|stop|status|restart[|running]"
  exit 1
  ;;
esac
exit $?
