#!/usr/bin/env /bin/bash
# modified by BK aug 2008

## If no parameter is provided then set user to 'root'
#[ "$1" ] && user=$1 || user=root

[ ! $1 ] && exit #BK

if [ "$1" = "stop" ];then #BK
 PIDPATH=/var/run/ipw3945d
 # Kill the regulatory daemon if it is running:
 /sbin/ipw3945d --isrunning --pid-file=${PIDPATH}/ipw3945d.pid && /sbin/ipw3945d --kill --pid-file=${PIDPATH}/ipw3945d.pid
 # Remove the PID directory
 [ -d ${PIDPATH} ] && rm -rf ${PIDPATH}
 exit
fi

[ "$1" != "start" ] && exit #BK

wait_for_cmd() {
	# First, wait for sysfs entry to show up, timing out after 10 seconds:
	count=0
	while [ ! -e /sys/bus/pci/drivers/ipw3945/*/cmd ]; do
		sleep 0.5
		count=$((count+1))
		((count > 20)) && return 1
	done

	return 0
}

wait_for_cmd && {
	# Set ownership of sysfs entry:
	chown $user /sys/bus/pci/drivers/ipw3945/*/cmd
	chmod a-w,u+rw /sys/bus/pci/drivers/ipw3945/*/cmd

	# Verify/set up PID directory 
	[ ! -d /var/run/ipw3945d ] && {
		mkdir -m 0775 /var/run/ipw3945d
		chown $user /var/run/ipw3945d
	}

	# Launch the regulatory daemon:
	/sbin/ipw3945d --quiet --pid-file=/var/run/ipw3945d/ipw3945d.pid
}
