#!/bin/sh
#
# wicd:   wicd daemon
#
# description:  This is a daemon managing network connections.
#
# processname: wicd-daemon
# pidfile: /var/run/wicd.pid
#
WICD_BIN=/opt/wicd/daemon.py

# Sanity checks.
[ -x $WICD_BIN ] || exit 0

PIDFILE=/var/run/wicd.pid
$WICD_EXEC="$WICD_BIN -P $PIDFILE"


wicd_start()
{
        if [ "`pgrep dbus-daemon`" = "" ]; then
    echo "D-BUS must be running to start wicd"
    return
        fi
 
  # Just in case the pidfile is still there, we may need to nuke it.
  if [ -e "$PIDFILE" ]; then
    rm -f $PIDFILE
  fi

  echo "Starting wicd daemon:  $WICD_BIN"
  $WICD_EXEC
}

wicd_status()
{
  local pidlist=`cat $PIDFILE 2>/dev/null`
  if [ -z "$pidlist" ]; then
    return 1
  fi
  local command=`ps -p $pidlist -o comm=`
  if [ "$command" != 'wicd-daemon' ]; then
    return 1
  fi
}

wicd_stop()
{
  echo -en "Stopping wicd: "
  local pidlist=`cat $PIDFILE 2>/dev/null`
  if [ ! -z "$pidlist" ]; then
    kill $pidlist &>/dev/null
    rm -f $PIDFILE &>/dev/null
        fi
  echo "stopped";
}

wicd_restart()
{
  wicd_stop
  wicd_start
}

case "$1" in
'start')
  if ( ! wicd_status ); then
    wicd_start
  else
    echo "wicd is already running (will not start it twice)."
  fi
                ;;
'stop')
  wicd_stop
                ;;
'restart')
  wicd_restart
                ;;
'status')
  if ( wicd_status ); then
    echo "wicd is currently running"
  else
    echo "wicd is not running."
  fi
                ;;
*)
  echo "usage $0 start|stop|status|restart"
esac

