#!/bin/bash
while true; do
	case "$1" in
		-*)
		if [ a"$1" = a"-n" ]; then
			# don't touch drive idle parameters
			idleignore=true
			export idleignore
		fi
		shift
		;;
		*)
		break
		;;
	esac
done


if [ "$1" = "" ]; then
  devices=$( awk '
		{ 
			if(length($4) == 3 ) 
				{ printf("/dev/%s\n",$4); } 
			endif; 
			next; }
		' < /proc/partitions
  )
else
  devices=$@
fi


rootdev=$( df /|awk '/\/dev\// {print substr($1,1,8);}' )


echo "devices:" $devices
echo "rootdev: $rootdev"



# wakeup everything:

pos 
pos

for i in $devices; do
  if [ "$idleignore" != "true" ]; then
    str=$( set_drive_spindown_timeout up $i 2>&1 ) || { echo "$i standby->0 :"; echo "$str"; echo "" ; }
  fi
    str=$( smartctl -q errorsonly -s on $i 2>&1 ) || { echo "$i smart->on :"; echo "$str"; echo "" ; }
    usleep 200
    str=$( smartctl -t long $i 2>&1 )
    said_it_takes=$( echo "$str"|awk '
				/^Please wait [0-9]* minutes for.*/ { print $3 ; } ' )

    if [ "$i" = "$rootdev" ]; then
	S=180
	B=126
	factor=110
    else
	S=120
	B=60
	factor=110
    fi

    outfile=$(echo $i|sed 's@/@_@g')
    outfile="/root/smart$outfile"

    date >> $outfile
    if [ "$said_it_takes" = "" ]; then
	echo "$i: smart test not executed. read $outfile"
	if [ "$idleignore" != "true" ]; then
	       {
		echo "$str"
		set_drive_spindown_timeout down $i
       		} >> $outfile 2>&1
	fi
    else

        seconds=$(( $said_it_takes * 60 ))
        sleeptime=$(( $seconds * $factor ))
        sleeptime=$(( $sleeptime / 100 ))
        sleeptime=$(( $sleeptime + 600 ))
        echo "$i: said_it_takes=$said_it_takes sleeptime=$sleeptime"

      (
	sleep $sleeptime
	smartctl -a $i > $outfile 2>&1
	if [ "$idleignore" != "true" ]; then
		set_drive_spindown_timeout down $i
	fi
      ) >> $outfile 2>&1 &

    fi
	

done

