#! /bin/sh

### BEGIN INIT INFO
# Provides:          sysfsconf
# Should-Start:      udev 
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Set sysfs variables from /etc/sysfs.conf
# Description:       Similarly to /etc/init.d/procps.sh, you can configure
#                    values for sysfs variables (such as power management
#                    defaults) and /sys file permissions in /etc/sysfs.conf.
### END INIT INFO

# /etc/init.d/sysfsutils: 
#
# (c) 2005 Martin Pitt <mpitt@debian.org>
# (c) 2013 Andrew Wyatt <andrew@fuduntu.org>

CONFFILE=/etc/sysfs.conf

[ -r "$CONFFILE" ] || (echo $"Configure sysfsutils"; exit 1)

# Source function library.
. /etc/init.d/functions

usage() {
    echo $"Usage: $0 {start|stop}"
    exit 1
}

case "$1" in
    start|restart|force-reload)
	echo -n $"Configuring sysfs parameters: "
	sed  's/#.*$//; /^[[:space:]]*$/d; 
              s/^[[:space:]]*\([^=[:space:]]*\)[[:space:]]*\([^=[:space:]]*\)[[:space:]]*=[[:space:]]*\(.*\)/\1 \2 \3/' \
              $CONFFILE | {
	    while read f1 f2 f3; do
                if [ "$f1" = "mode" -a -n "$f2" -a -n "$f3" ]; then
                    if [ -f "/sys/$f2" ] || [ -d "/sys/$f2" ]; then
                        chmod "$f3" "/sys/$f2"
                    fi
                elif [ "$f1" = "owner" -a -n "$f2" -a -n "$f3" ]; then
                    if [ -f "/sys/$f2" ]; then
                        chown "$f3" "/sys/$f2"
                    fi
                elif [ "$f1" -a -n "$f2" -a -z "$f3" ]; then
                    if [ -f "/sys/$f1" ]; then
                        # Some fields need a terminating newline, others
                        # need the terminating newline to be absent :-(
                         echo -n "$f2" > "/sys/$f1" 2>/dev/null ||
                            echo "$f2" > "/sys/$f1"
                    fi
                else
		    action "" /bin/false
		    exit 1
                fi
	    done
	}
	action "" /bin/true
	exit 0
	;;
    stop)
	action "" /bin/true
	exit 0
	;;
esac

