#!/bin/sh

# TO DO
# pmset -g assertions
#   pid 419(coreaudiod): [0x0000a7e0000192db] 02:57:46 PreventUserIdleSystemSleep named: "com.apple.audio.AppleUSBAudioEngine:Burr-Brown from TI              :USB Audio DAC   :3200000:1.context.preventuseridlesleep"  
#        Created for PID: 2213. 

export PATH=$PATH:/usr/bin/local
cname=`scutil --get ComputerName`
export CNAME=$cname
pmt=/tmp/pmset-test.txt
pmv=/tmp/pmset-videowakepids.txt
pidf=/tmp/pmset-test-pid.txt

echo ""
echo ""
echo "// idlecheck_quitvideowake"
echo "----------------------------------------------"

pmset -g assertions > ${pmt}

echo "" > ${pmv}
fgrep "Video Wake Lock" ${pmt} | sed 's/^.*pid \([0-9]\{1,6\}\)(\(.*\)).*$/\1 \2/' > ${pmv}

tsize=`stat -f%z ${pmv}`
#echo "file size: ${tsize}"
zs=0

if [ $tsize -gt 0 ]; then
	cat ${pmv} | while read line
	do
		pid=$(echo $line | awk '{print $1}')
		name=$(echo $line | awk '{print $2}')
		#echo "PID: ${pid}"
		#echo "NAME: ${name}"
		echo "* quitting Video Wake Lock Process: ${name} (${pid})"
		osascript -e "ignoring application responses" -e "quit app \"$name\"" -e "end ignoring"
		sleep 3
		ps -p ${pid} > ${pidf}
		pfsz=`stat -f%z ${pidf}`
		if [ $pfsz -gt 40 ]; then
			echo "  killing pid as script didn't kill it? pid ${pid}"
			sleep 3
			kill -9 $pid
		else
			echo "  quit successfully!"
		fi
	done 
else
	echo "* no Video Wake Lock processes"
fi


if [ -f "${pmt}" ]; then rm ${pmt}; fi
if [ -f "${pmv}" ]; then rm ${pmv}; fi
if [ -f "${pidf}" ]; then rm ${pidf}; fi
