#!/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-audiolockpids.txt
pidf=/tmp/pmset-test-pid.txt

echo ""
echo ""
echo "// idlecheck_quitaudiolock"
echo "----------------------------------------------"

pmset -g assertions > ${pmt}

echo "" > ${pmv}
# fgrep "Video Wake Lock" ${pmt} | sed 's/^.*pid \([0-9]\{1,6\}\)(\(.*\)).*$/\1 \2/' > ${pmv}
lastlineps=0
cat ${pmt} | while read line
do
#	echo $line
	if [[ $line =~  fgb3 ]]; then
		if [ "$lastlineps" -eq 1 ]; then
			echo $'\t' "^^ want to kill this PID"
		fi
	fi
	if [[ $line =~ .*preventuseridlesleep.* ]]; then
		echo $'\t' "^^ prevent"
		lastlineps=1
	else
		lastlineps=0
	fi
done


# fgrep "Created for PID:" ${pmt} | sed 's/^.*PID: \([0-9]\{1,6\}\).*$/\1/' > ${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 $'\t' "killing pid as script didn't kill it? pid ${pid}"
#			sleep 3
#			kill -9 $pid
#		else
#			echo $'\t' "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
