#!/bin/bash
#
# **** License ****
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available as
# `/usr/share/common-licenses/GPL' in the Debian GNU/Linux distribution
# or on the World Wide Web at `http://www.gnu.org/copyleft/gpl.html'.
# You can also obtain it by writing to the Free Software Foundation,
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.
# 
# This code was originally developed by Vyatta, Inc.
# Portions created by Vyatta are Copyright (C) 2009 Vyatta, Inc.
# All Rights Reserved.
# 
# Author: Stephen Hemminger
# Date: August 2009
# 
# **** End License ****

# Based on Debian /etc/init.d/hostapd

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/hostapd

if [ $# -ne 2 ]; then
    echo "Usage: $0 {start|stop|restart} wlanX" >&2
    exit 1
fi

pid_dir=/var/run/hostapd
mkdir -p $pid_dir

DEVICE=$2
pid_file=$pid_dir/$DEVICE.pid
config=$pid_dir/$DEVICE.cfg

DAEMON_OPTS="-B -P $pid_file $config"

do_start()
{
    start-stop-daemon --start --quiet \
	--chdir $pid_dir --pidfile $pid_file \
	--exec $DAEMON -- $DAEMON_OPTS > /dev/null
}

do_stop()
{
    if [ -r $pid_file ]; then
	start-stop-daemon --stop --quiet --pidfile $pid_file --exec $DAEMON
	rm -f $pid_file
    fi
}


do_status()
{
    if [ ! -r $pid_file ]; then
	echo "$DAEMON is not running."
	exit 3
    elif read pid < $pid_file && ps -p "$pid" > /dev/null 2>&1; then
	echo "$DAEMON is running."
	exit 0
    else
	echo "$DAEMON is not running but $pid_file exists."
	exit 1
    fi
}

case "$1" in
  start)
	do_start
	;;
  stop)
	do_stop
	;;
  status)
	do_status
	;;
  reload)
	start-stop-daemon --stop --signal HUP --quiet  \
	    --pidfile $pid_file --exec $DAEMON
	;;
  restart|force-reload)
	do_stop
	do_start
	;;
  *)
	echo "Usage: $0 {start|stop|restart|force-reload} wlanX" >&2
	exit 1
	;;
esac
