#! /bin/sh
#
# Laptop mode tools module: Power management for Intel SATA controllers
#

if [ x$CONTROL_INTEL_SATA_POWER = x1 ] || [ x$ENABLE_AUTO_MODULES = x1 -a x$CONTROL_INTEL_SATA_POWER = xauto ]; then
	# Set defaults (these settings were added later)
	if [ -z "$BATT_SATA_POLICY" ]; then
		if [ -z "$BATT_ACTIVATE_SATA_POWER" -o "$BATT_ACTIVATE_SATA_POWER" -eq 1 ]; then
			BATT_SATA_POLICY=min_power
		else
			BATT_SATA_POLICY=max_performance
		fi
	fi
	if [ -z "$LM_AC_SATA_POLICY" ]; then
		if [ "$LM_AC_ACTIVATE_SATA_POWER" -eq 1 ]; then
			LM_AC_SATA_POLICY=min_power
		else
			LM_AC_SATA_POLICY=max_performance
		fi
	fi
	if [ -z "$NOLM_AC_SATA_POLICY" ]; then
		if [ "$NOLM_AC_ACTIVATE_SATA_POWER" -eq 1 ]; then
			NOLM_AC_SATA_POLICY=min_power
		else
			NOLM_AC_SATA_POLICY=max_performance
		fi
	fi

	# Determine setting
	if [ $ON_AC -eq 1 ]; then
		if [ "$ACTIVATE" -eq 1 ]; then
			SATA_POLICY="$LM_AC_SATA_POLICY"
		else
			SATA_POLICY="$NOLM_AC_SATA_POLICY"
		fi
                RUNTIME_PM_AHCI="on"
	else
		SATA_POLICY="$BATT_SATA_POLICY"
                RUNTIME_PM_AHCI="auto"
	fi

	for POLICYFILE in /sys/class/scsi_host/*/link_power_management_policy ; do
		if [ -f $POLICYFILE ] ; then
			log "VERBOSE" "Intel SATA link power saving set to $SATA_POLICY for $POLICYFILE."
			echo $SATA_POLICY > $POLICYFILE
		else
			log "VERBOSE" "Intel SATA link power saving enabled but not supported by system for $POLICYFILE."
		fi
	done

        if [ x$CONTROL_AHCI_RUNTIME_PM = x1 ]; then 
                # Enable Runtime PM for AHCI Class Ports
                for port in /sys/bus/pci/devices/*/ata*/power/control ; do
                        if [ -f $port ]; then
                                log "VERBOSE" "Setting AHCI Runtime PM value for $port to value: $RUNTIME_PM_AHCI"
                                echo $RUNTIME_PM_AHCI > $port;
                        fi
                done

                # Now scan through available devices that are marked for power savings
                # Let's scan through all block devices, typically there aren't many, even after considering the virtual block devices
                for device in /sys/block/*/device/power/control ; do
                        if [ -f $device ]; then
                                log "VERBOSE" "Setting AHCI Runtime PM value for $device to value: $RUNTIME_PM_AHCI"
                                echo $RUNTIME_PM_AHCI > $device;
                        fi
                done
        else
                log "VERBOSE" "AHCI Runtime PM is disabled"
        fi
else
	log "VERBOSE" "Intel SATA link power saving disabled."
fi

