#!/bin/sh

export PATH=$PATH:/usr/bin/local
cname=`scutil --get ComputerName`
export CNAME=$cname
pmt=/tmp/pmset-test.txt
pmv=/tmp/pmset-caffeinatepids.txt
pidf=/tmp/pmset-test-pid.txt
dnqf=/tmp/caffeinate-do-not-quit.txt

doNotQuit=("Hogwasher" "HandBrake" "PreventUserIdleSleep" "ffmpeg" "Amphetamine") # last val actually not a prog output
preventButOK=("powerd" "cloudd" "bluetoothd" "coreaudiod")
# https://textkool.com/en/test-ascii-art-generator?text=idlecheck
# "ANSI Shadow" font
echo ""
echo ""
echo "// idlecheck_caffeinatestuck"
echo "----------------------------------------------"

#Listed by owning process:
# pid 30456(caffeinate): [0x00004a4700018c74] 15:16:59 PreventUserIdleSystemSleep named: "caffeinate command-line tool"
#Details: caffeinate asserting on behalf of '/Users/shughey/Dropbox/bin/presleep' (pid 30455)
#Localized=THE CAFFEINATE TOOL IS PREVENTING SLEEP.
# pid 30456(caffeinate): [0x00004a4700078c77] 15:16:59 PreventSystemSleep named: "caffeinate command-line tool"
#Details: caffeinate asserting on behalf of '/Users/shughey/Dropbox/bin/presleep' (pid 30455)
#Localized=THE CAFFEINATE TOOL IS PREVENTING SLEEP.

pmset -g assertions > ${pmt}
#cat test-caffeinate.txt > ${pmt}

echo "" > ${pmv}
rm ${dnqf}
touch ${dnqf}

fgrep "PreventUserIdleSystemSleep named" ${pmt} | grep pid | cut -d : -f 1,1 | sed 's/^.*pid \([0-9]\{1,6\}\)(\(.*\)).*$/\1 \2/' > ${pmv}

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

#cat ${pmt} # test

if [ $tsize -gt 0 ]; then
	cat ${pmv} | while read line
	do
#        echo $line
		pid=$(echo $line | awk '{print $1}')
		name=$(echo $line | awk '{print $2}')
#		echo "PID: ${pid}"
#		echo "NAME: ${name}"
		if [[ ! " ${doNotQuit[*]} " =~ [[:space:]]${name}[[:space:]] ]]; then
#		if [[ "$name" != "PreventUserIdleSystemSleep" && "$name" != "cloudd" ]]; then
			if [[ ! " ${preventButOK[*]} " =~ [[:space:]]${name}[[:space:]] ]]; then # is it on the Prevent but sleep anyway list? ex: powerd
				echo "* quitting: ${name} (PreventUserIdleSystemSleep, id ${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
			fi
		else
			echo "* skipping from Do Not Quit list: ${name}"
			echo ${name} >> ${dnqf}
		fi
	done 
else
	echo "* no PreventUserIdleSystemSleep"
fi

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