#!/bin/bash
#
# description:	Set sysfs variables from /etc/sysfs.conf

. /etc/rc.conf
. /etc/rc.d/functions

CONFIG=/etc/sysfs.conf
LOCKFILE=/var/lock/subsys/sysfs

config_error () {
	local lineno="$1" && shift
	echo "$CONFIG:$lineno: $*" >&2
}

apply_sysfs_rules () {
	local lineno=0 ret=0

	while read f1 f2 f3 f4; do
		lineno=$(( $lineno + 1 ))

		# Skip empty lines
		[ -z "$f1$f2$f3$f4" ] && continue
		# Skip comments
		[ -n "$f1" -a -z "${f1##\#*}" ] && continue

		case "$f1,$f2,$f3,$f4" in
			mode,?*,=,?*)
				if [ -f "/sys/$f2" ]; then
					chmod "$f4" "/sys/$f2" || ret=1
				else
					echo "Unknown attribute: $f2" >&2
				fi
				;;

			owner,?*,=,?*)
				if [ -f "/sys/$f2" ]; then
					chown "$f4" "/sys/$f2" || ret=1
				else
					echo "Unknown attribute: $f2" >&2
				fi
				;;
				
			?*,=,?*,)
				if [ -f "/sys/$f1" ]; then
					echo -n "$f3" > "/sys/$f1" || ret=1
				else
					echo "Unknown attribute: $f1" >&2
				fi
				;;

			*,*,*,*)
				config_error $lineno "Synax error: $f1 $f2 $f3 $f4"
				return 1
				;;
		esac
	done < "$CONFIG"

	return $ret
}

# See how we were called.
case "$1" in
	start)
		stat_busy "Setting sysfs variables"
		if [ ! -f $CONFIG ]; then
			echo "Cannot load sysfs config: $CONFIG is missing!" >&2
			exit 1
		fi

		if ck_daemon sysfs; then
			apply_sysfs_rules
			if [ $? == 0 ]; then
				add_daemon sysfs
				stat_done
			else
				echo "Error appling sysfs settings" >&2
				stat_fail
			fi
		else
			echo "Sysfs settings already applied" >&2
			stat_fail
		fi
		;;
	stop)
		rm_daemon sysfs
		;;
	restart)
		$0 stop
		$0 start
		;;
	*)
		echo "usage: $0 {start|stop|restart}"
esac

exit 0
