#!/bin/sh
#=================================================================
#
# Description : Start hostap daemon
# chkconfig: 2345 23 88
#
#=================================================================

### BEGIN INIT INFO
# Provides:            $hostapd
# Required-Start:      $network
# Should-Start:
# Required-Stop:       
# Should-Stop:
# Default-Start:       3 4 5
# Default-Stop:        0 1 2 6
# Short-Description:   Starts hostapd daemon.
# Description:         Starts hostapd daemon.
### END INIT INFO

. /lib/lsb/init-functions

PROG="hostapd"
BIN_FILE="/usr/sbin/${PROG}"

# PID directory
PIDDIR="/run/${PROG}"

#configuration directory
CONFDIR="/etc/${PROG}"

#=============================================================
#procedure stop or start ONE hostapd definition
#$1  start|stop
#$2  the hostapd definition list
#-------------------------------------------------------------
oneact()

{
case "$1" in
  "start"       )
    mkdir -p ${PIDDIR}
    log_info_msg "Starting $PROG, $2"
    ${BIN_FILE}						\
       	-B						\
	-P ${PIDDIR}/$2.pid				\
	${CONFDIR}/$2.conf				\
	> /dev/null
    evaluate_retval
    ;;
  "stop"        )
    if [ -f ${PIDDIR}/$2.pid ] ; then
      log_info_msg "Stopping $PROG, $2"
      kill `cat ${PIDDIR}/$2.pid` > /dev/null 2>&1
      evaluate_retval
      rm -f						\
	      ${PIDDIR}/$2.pid 
      fi
    ;;
  esac
}
#=============================================================
#procedure stop or start each hostapd definition
#$1  start|stop
#$2  the hostapd definition list
#-------------------------------------------------------------
allact()

{
COUNT=0
ACTION=$1
shift;
if [ $# -gt 0 ] ; then
  for apd in $*
    do
    oneact $ACTION ${apd}
    COUNT=`echo "(${COUNT}+1)" | bc`
    done
  fi
if [ ${COUNT} -eq 0 ] ; then
  for def in `/bin/ls /etc/${PROG}/*.conf 2>/dev/null`
    do
    apd=`basename ${def%%.conf}`
    oneact $ACTION ${apd}
    COUNT=`echo "(${COUNT}+1)" | bc`
    done
  fi
if [ ${COUNT} -eq 0 ] ; then
  log_info_msg "$PROG, found NO %{PROG} definition to ${ACTION}"
  true
  evaluate_retval
  fi
}

#=============================================================

case "$1" in
    start)
      allact $*
      ;;

    stop)
      allact $*
      ;;

    restart)
	shift
        $0 stop  $*
	sleep 3
        $0 start $*
        ;;

    condrestart)
        ;;

    status)
        ;;

    *)
        echo "Usage: $0 {start|stop|restart|condrestart|status}"
        exit 1
        ;;
esac

