#!/bin/sh

rtbt_restore=/tmp/rtbt_pre
rfkill_list="rfkill0 rfkill1 rfkill2 rfkill3 rfkill4 rfkill5 rfkill6 rfkill7 rfkill8 rfkill9 rfkill10 rfkill11 rfkill12 rfkill13 rfkill14 rfkill15 rfkill16"
rfkill_found=0

rtbt_off() {

if [ -f "/tmp/rtbt_pre" ]; then
        echo "/tmp/rtbt_pre exist"
else
        touch $rtbt_restore
fi

echo 1 > $rtbt_restore

for rfkill in $rfkill_list; do 
if [ -d "/sys/class/rfkill/$rfkill" ]; then
	echo "$rfkill exist"
else
	continue 	
fi

type=`cat /sys/class/rfkill/$rfkill/type`
if [ "$type" = "bluetooth" ]; then
	echo "bluetooth found on $rfkill"
else 
	continue 
fi

state=`cat /sys/class/rfkill/$rfkill/soft`
if [ $state -eq 0 ]; then
	echo 0 > $rtbt_restore
	echo "bluetooth on state"
	echo "bluetooth turnning off ... start"
	echo 1 > /sys/class/rfkill/$rfkill/soft 
	echo "bluetooth turning off ... end"
else 
	echo "bluetooth off state, nothing to do"	
fi

done
}

rtbt_restore() {
for rfkill in $rfkill_list; do
if [ -d "/sys/class/rfkill/$rfkill" ]; then
	echo "$rfkill exist"
else
        continue
fi

type=`cat /sys/class/rfkill/$rfkill/type`
if [ "$type" = "bluetooth" ]; then
        echo "bluetooth found on $rfkill"
else
        continue
fi

rtbt_pre=`cat $rtbt_restore`
echo "bluetooth restoring ... prestate=$rtbt_pre"
echo $rtbt_pre > /sys/class/rfkill/$rfkill/soft

done
} 

case "$1" in
	suspend|hibernate)
                rtbt_off
                ;;
        resume|thaw)
                rtbt_restore
                ;;
esac
exit 0
