#!/bin/bash
#
# sysfsutils	This set /sys directory local adjstment
#
# chkconfig:	2345 60 40
# description:  This set local /sys parameter according /etc/sysfs.conf
#		contents
#
#
### BEGIN INIT INFO
# Provides:            sysfsconf
# Required-Start:      lm-sensors
# Default-Start:       2 3 4 5
# Default-Stop:        0 1 6
# Short-Description:   set local /sys parameters
### END INIT INFO


PATH=/sbin:/bin:/usr/bin:/usr/sbin

# Source function library.
. /lib/lsb/init-functions

PROG=sysfsutils
CONFFILE=/etc/sysfs.conf
CONFDIR=/etc/sysfs.d

load_conffile()

{
FILE="$1"

( cat "$FILE"; echo ) |
  sed  's/#.*$//; /^[[:space:]]*$/d;
        s/^[[:space:]]*\([^=[:space:]]*\)[[:space:]]*\([^=[:space:]]*\)[[:space:]]*=[[:space:]]*\(.*\)/\1 \2 \3/' |
  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"
      else
        log_failure_msg "unknown attribute $f2"
      fi
    elif [ "$f1" = "owner" -a -n "$f2" -a -n "$f3" ]; then
      if [ -f "/sys/$f2" ]; then
        chown "$f3" "/sys/$f2"
      else
        log_failure_msg "unknown attribute $f2"
      fi
    elif [ "$f1" -a -n "$f2" -a -z "$f3" ]; then
      for path in /sys/$f1; do
        if [ -f "$path" ]; then
          # Some fields need a terminating newline, others need the
          # terminating newline to be absent. :-(
          echo -n "$f2" >"$path" 2>/dev/null ||
          echo "$f2" >"$path" 2>/dev/null ||
          log_failure_msg "cannot write value for attribute $f1"
        else
          log_failure_msg "unknown attribute $f1"
        fi
      done
    else
      log_failure_msg "syntax error in $FILE: '$f1' '$f2' '$f3'"
      log_action_end_msg 1
      exit 1
    fi
  done
}

# Some functions to make the below more readable
case "$1" in
    start)
      log_info_msg "Starting $PROG process..."
      for file in $CONFFILE $CONFDIR/*.conf; do
	[ -r "$file" ] || continue
        load_conffile $file
        done
      evaluate_retval
      ;;

    stop)
      ;;

    restart)
        $0 stop
        sleep 1
        $0 start
        ;;

    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

