#!/usr/bin/env /bin/bash
# If no parameter is provided then set user to 'root'
[ "$1" ] && user=$1 || user=root

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
}
