# -*- sh -*-
# vim:ft=sh:ts=8:sw=4:noet

AddConfigHandler DevicesOptions
AddConfigHelp "IncompatibleDevices <device name> [...]" "If there are any processes accessing these devices, then suspending is aborted. If the --kill option is passed, the offending processes are terminated and the suspend continues. For example programs accessing the sound card (/dev/dsp*) or tuner cards (/dev/video*) would deny the respective modules from being unloaded."

DevicesFree() {
    local needsleep # always! ;)
    local device
    local ret

    [ -z "$INCOMPATIBLE_DEVICES" ] && return 0

    needsleep=0

    # Send TERM to processes first
    if [ x"$KILL_PROGRAMS" = "x1" ] ; then
	for device in $INCOMPATIBLE_DEVICES ; do
	    if fuser -s $device ; then
		vecho 1 "Sending SIGTERM to processes using $device..."
		fuser -s -k -15 $device 2>/dev/null
		fuser -s $device && needsleep=1
	    fi
	done
    fi

    [ "$needsleep" -eq 1 ] && sleep 1

    # Send KILL to processes
    ret=0
    for device in $INCOMPATIBLE_DEVICES ; do
	if fuser -s $device ; then
	    if [ x"$KILL_PROGRAMS" = "x1" ] ; then
		vecho 1 "Sending SIGKILL to processes using $device..."
		fuser -s -k -9 $device 2>/dev/null
	    else
		vecho 1 "Device $device is still in use by the following processes: `fuser $device 2>/dev/null`"
		ret=1
	    fi
	fi
    done

    # We tried our best.
    return $ret
}

DevicesOptions() {
    case $1 in
	incompatibledevices)
	    # we have to kill before are services stopped, modules unloaded.
	    # but should it run before programs, I suggest yes!
	    [ -z "$INCOMPATIBLE_DEVICES" ] && AddSuspendHook 19 DevicesFree
	    shift
	    INCOMPATIBLE_DEVICES="$INCOMPATIBLE_DEVICES $@"
	    ;;
	*)
	    return 1
    esac
    return 0
}

# $Id: devices 1139 2007-07-16 12:33:07Z nigel $
