#! /bin/sh
# Copyright (c) 2002, 2003 SuSE Linux AG, Nuernberg, Germany. All rights reserved.
#
# File: /etc/init.d/boot.idedma
# Author: Ladislav Slezak <lslezak@suse.cz>
#
# System startup script for enabling/disabling IDE DMA mode
#
### BEGIN INIT INFO
# Provides:          boot.idedma
# Required-Start:    boot.loadmodules
# Required-Stop:
# Default-Start:     B
# Default-Stop:
# Description:       Enable/disable DMA mode on IDE devices.
### END INIT INFO

HDPARM=/sbin/hdparm
test -x $HDPARM || exit 5

# source rc functions
. /etc/rc.status

# First reset status of this service
rc_reset

# read values from sysconfig
. /etc/sysconfig/ide

# enable/disable DMA mode
function idedma_main() {
    local MODE DEVICE OPTIONS FIRST
    if [ "$DEVICES_FORCE_IDE_DMA" = "" ] ; then
	exit 0;
    fi

    echo "Setting up IDE DMA mode"

    OLDIFS=$IFS
    for dev in $DEVICES_FORCE_IDE_DMA ; do
	# Get device and DMA mode

	MODE=""
	DEVICE=""
	OPTIONS=""
	FIRST=0

	# The setting e.g. "/dev/hda:69:-c1:-m16:-u1:-W1:-A1" should be
	# expanded as "hdparm -d 1 -X 69 -c1 -m16 -u1 -W1 -A1 /dev/hda"

	IFS=":"
	for d in $dev ; do
	    case $((FIRST++)) in
	    0) DEVICE=$d ;;
	    1) MODE=$d   ;;
	    *) OPTIONS="$OPTIONS$d:"
	    esac
	done
	unset d

	# Set DMA mode by hdparm utility
	if [ -z "$MODE" ] ; then
	    echo "Missing DMA mode for device $DEVICE"
	    rc_failed  
	elif [ $MODE = "off" ] ; then
	    $HDPARM -d 0 "$DEVICE" || rc_failed
	elif [ $MODE = "on" ] ; then
	    $HDPARM -d 1 "$DEVICE" || rc_failed
	else
	    $HDPARM -d 1 -X "$MODE" ${OPTIONS:+$OPTIONS} "$DEVICE" || rc_failed
	fi

	# Reset Internal Field Separator for the outer loop
	IFS=$OLDIFS
    done
    unset dev

    rc_status -v
}


case "$1" in
    start|restart)
	idedma_main
	;;
    stop)
	# skip / nothing to do
	;;
    try-restart)
	## Stop the service and if this succeeds (i.e. the 
	## service was running before), start it again.
	## Note: try-restart is not (yet) part of LSB (as of 0.7.5)
	$0 status >/dev/null && $0 restart

	# Remember status and be quiet
	rc_status
	;;
    force-reload)
	## Otherwise:
	$0 restart
	rc_status
	;;
    reload)
	## reload is not supported
	rc_failed 3
	rc_status -v
	;;
    status)
	echo "IDE DMA mode status: "

	for dev in /proc/ide/hd[a-l]; do
	    device=`basename $dev`
	    $HDPARM -d /dev/$device 2> /dev/null
        done

	# service is not running
	rc_failed 3
	;;
    probe)
	## Optional: Probe for the necessity of a reload,
	## give out the argument which is required for a reload.
	;;
    *)
	echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload|probe}"
	exit 1
	;;
esac
rc_exit
