#!/bin/bash
#
# Power Consumption test script, which brings selected devices in D3 and back
# to D0, for a specific duration. The script creates a log file named:
#
# > consumption_report.UNIX_TIME_STAMP
#
# This scripts contains date of test, lspci output of test machine, 
# and point of time of D0 D3 transition.
# This script should be used in a test environment like described in:
# http://powersave.sf.net/pm-report/ 


RCNETWORK="rcnetwork";	# runlevel network script to start/stop network devices

LOGFILE="consumption_report.$( date +%s)";


# Interal File Seperator (man bash - for more details) - don't change this - IFS="\n"
IFS="
"

if ! [ $1 ]; then
	echo "usage: $0 <seconds>";
	echo "sleeping time is missing!";
	exit 0;
fi;

#
#
#
#echo "Sync time on the other machine & plug-in LAN cable! Press a Key.";
#read;
#SuSEfirewall2 stop
#ifdown ethX
#ntpdate ntp1.xxxxxxx.xx 

echo -n "Synced time on the other machine? (No sync, no correct graph) [yN] ";
read synced;

if ! [ "$synced" = "y" -o "$synced" = "Y" ]; then
	echo "Please, sync the time before running $0!";
	echo "$0 stopped.";
	exit -1;
fi;

# no Ethernet connection - less consumption
echo "Remove LAN cable and Press a key...";
read;

$RCNETWORK stop;

echo "Run QtDMM on the measurement-terminal and start...";
read;

touch $LOGFILE; 
echo "Power Consumption Report - $(date)" >> $LOGFILE;
echo -e "\n$(lspci)\n" >> $LOGFILE;


BEGIN=$( date +%X );

SLEEP_DEVICES="";


# Preselection of PCI devices

# Choose devices - line by line:
for n in `lspci`; do
	PCIID="$(echo -n $n | cut -c -7)"
	FULLNAME="$(echo -n $n | cut -c 9-)";
	STATEFILE="/sys/bus/pci/devices/0000:$PCIID/power/state";
	SUSPEND="";
	
	if [ -f $STATEFILE ]; then
		
		echo -n "$FULLNAME >> suspend? [yN] ";
		read SUSPEND;

			if [ "$SUSPEND" = "y" ]; then
				SLEEP_DEVICES="$SLEEP_DEVICES $PCIID"
				echo .
			else
				echo "skipped."
			fi;
				
	fi;
done;

echo "Testing devices:" $SLEEP_DEVICES;

# reset IFS to " \t\n"
IFS=" 	
"

# Sleeping time...
for n in $SLEEP_DEVICES; do
	PCIID=$n
	FULLNAME="$(lspci | grep $PCIID | cut -c 9-)";
	STATEFILE="/sys/bus/pci/devices/0000:$PCIID/power/state";
	SUSPEND="";
	
	echo -n "$(date +%X) $FULLNAME: "
	if [ -f $STATEFILE ]; then
		
			echo -n "$(date +%X) $PCIID $FULLNAME: " >> $LOGFILE;
			echo -n " changing to [D3]";
			echo "changed to D3" >> $LOGFILE;
			echo -n 3 > $STATEFILE; 	# XXX :)
			echo ".";
			echo "sleeping for $1 seconds.";
			sleep $1;
			echo -n "changing to [D0]";
			echo "$(date +%X) $PCIID $FULLNAME: back to D0" >> $LOGFILE;
			echo -n 0 > $STATEFILE;	# XXX :P
			echo ".";
				
fi;

# the last $1 seconds are important to get the idle consumption of the test system
echo "sleeping $1 s for a clean graph..."; 
sleep $1;

echo >> $LOGFILE;
done;

END=$(date +%X);

echo "BEGIN:$BEGIN END:$END" >> $LOGFILE;

echo "Stop QtDMM - on the other machine...";
read;

echo "Plug in the LAN cable...";
read;

$RCNETWORK start;
echo -e "$0: \033[1mfinished\033[0m.";
