#!/bin/sh

. "${PM_FUNCTIONS}"

SATA_ALPM_ENABLE=${SATA_ALPM_ENABLE:-false}

help() {
cat <<EOF
$0: SATA link power management

This hook tries to save power by allowing SATA controllers to
reduce power usage when the SATA subsystem is otherwise idle.

This adds a little bit of latency to drive accesses in
exchange for moderate power savings if you are not using the drive.

This hook has 1 parameter:
SATA_ALPM_ENABLE = whether to use SATA ALPM on battery.
Defaults to "false".

EOF
}

set_sata_alpm() {
    # see kernel commit 6013efd8860bf15c1f86f365332642cfe557152f
    kv="$(uname -r)"
    [ "$kv" ] || exit $NA  #for paranoia's sake
    [ "${kv%-*}" \< "2.6.33" ] && exit $NA  # avoid fs corruption
    for f in /sys/class/scsi_host/host*; do
	[ -w "$f/link_power_management_policy" ] || continue
	printf "Setting SATA APLM on %s to %s..." "${f##*/}" "$1"
	echo "$1" > "$f/link_power_management_policy" && echo Done. || \
	    echo Failed.
    done
}

case $1 in
    true) [ "$SATA_ALPM_ENABLE" = true ] && set_sata_alpm min_power;;
    false) set_sata_alpm max_performance;;
    help) help;;
    *) exit $NA;;
esac

exit 0