#!/bin/bash
export PATH=$PATH:/usr/bin/local
cname=`scutil --get ComputerName`
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
dtst=`date +"%Y%m%d-%H.%M"`

echo "// presleep_quitapps"
echo "  " `date`
echo "   Machine: ${cname}"
echo "   Script: " `basename $0`
echo "  " `/usr/bin/sw_vers`
echo "  " `sysctl kern.version`
echo "  " `sysctl kern.ostype`
echo "  " `sysctl kern.osrelease`
echo "  " `sysctl kern.osrevision`
echo ""
echo ""
echo ""
echo "██╗██████╗ ██╗     ███████╗                 "
echo "██║██╔══██╗██║     ██╔════╝                 "
echo "██║██║  ██║██║     █████╗                   "
echo "██║██║  ██║██║     ██╔══╝                   "
echo "██║██████╔╝███████╗███████╗                 "
echo "╚═╝╚═════╝ ╚══════╝╚══════╝                 "
echo "                                            "
echo "     ██████╗██╗  ██╗███████╗ ██████╗██╗  ██╗"
echo "    ██╔════╝██║  ██║██╔════╝██╔════╝██║ ██╔╝"
echo "    ██║     ███████║█████╗  ██║     █████╔╝ "
echo "    ██║     ██╔══██║██╔══╝  ██║     ██╔═██╗ "
echo "    ╚██████╗██║  ██║███████╗╚██████╗██║  ██╗"
echo "     ╚═════╝╚═╝  ╚═╝╚══════╝ ╚═════╝╚═╝  ╚═╝"
echo ""
echo "--------------------------------------------"

if [[ $name = "Callum" ]]; then
  HC_TKN="spFBeVc0RciFezbuU8vfA"
else
  HC_TKN="Ew2r577TQShzrOH3Cmfew"
fi

# machine specific: Angus && Petula, turn off HomeKit stuff
if [[ $cname = "Angus" || $cname = "Petula" ]];
then
  echo "** Machine Specific: $cname"
  echo $'\t' "turning off xDuoo DAC using homecontrol"
  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=xDuoo%20DAC&room-name=South%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
  sleep 5
  echo $'\t' "turning off iFi DAC using homecontrol"
  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=DAC%20Stack&room-name=North%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
  sleep 5
  echo $'\t' "turning off South Office Lights using homecontrol"
  echo $'\t\t' "Antler Hue"
  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=Antler%20Hue&room-name=South%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
  sleep 5
  echo $'\t\t' "Hue Pole"
  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=Hue%20Pole&room-name=South%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
  sleep 5
  echo $'\t\t' "Desk Play L"
  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=Desk%20Play%20L&room-name=South%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
  sleep 5
  echo $'\t\t' "Desk Play R"
  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=Desk%20Play%20R&room-name=South%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
#  sleep 5
#  echo $'\t' "turning off North Office Lights using homecontrol"
#  echo $'\t\t' "Floor Lamp"
#  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=Floor%20Lamp&room-name=North%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
#  sleep 5
#  echo $'\t\t' "Hue Go"
#  open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=Hue%20Go&room-name=North%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
 # open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=PC%20Light%20Bars&room-name=North%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
 # open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=North%20Office%20TV%20Bias&room-name=North%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
# echo $'\t' "turning off Office Xmas Tree using homecontrol"
  # open -g "homecontrol://x-callback-url/run-action?action-type=switch-device-status&item-type=device&item-name=Office%20Tree&room-name=South%20Office&home-name=Holland%20Main&activation-mode=deactivate&authentication-token=${HC_TKN}"
  #echo $'\t' "^ TEMP DISABLED DUE TO NEW HOUSE/NO SETUP"

fi

echo -e "\n\n\n"
echo "** Assertions **"
echo "pmset -g assertions"
/usr/bin/pmset -g assertions

echo -e "\n\n\n"
echo "** Screen Captures **"
DC=$(osascript ${SCRIPT_DIR}/displaycount.scpt)
counter=1

mvar=( )
mkdir -p $HOME/ownCloud/Screen\ Shots/SleepShots
until [ $counter -gt ${DC} ]
do
  ssf="${cname}-${dtst}-${counter}.png"
  #echo "screencapture -D ${counter} ${ssf}"
  screencapture -x -D ${counter} $HOME/Desktop/${ssf}
  echo $'\t' "captured screen ${counter}, saved to ${ssf}"
  mvar+=("${ssf}")
  ((counter++))
done

for fn in "${mvar[@]}"
do
  mv $HOME/Desktop/${fn} $HOME/ownCloud/Screen\ Shots/SleepShots/
done

echo -e "\n\n\n"
echo "** Quitting Applications **"

prg=( "Zen Browser" "Opera" "Opera" "Opera" "Opera" "Opera" "Brave Browser" "MenubarX" "App Store" "WhatsApp" ".Agenda" "Steam" ".Loopback" ".Slack" "Boom 3D" "Paw" "DYMO Label" "QuickTime Player" "System Information" "Permute" "Activity Monitor" ".Transmit" ".Mail" ".Edison Mail" ".Airmail" "Setapp" ".Messages" "News" "zoom.us" "Preview" "Arq" "Carbon Copy Cloner" "Safari" "Vivaldi" "Firefox" "firefox" "Music" "Microsoft Edge" ".Parallels Desktop" ".Paw" ".Creative Cloud" "Things" ".Microsoft Word" ".Microsoft Excel" ".Microsoft PowerPoint" ".Xcode" "Simulator" "Audio Hijack" "Microsoft AutoUpdate" ".ToothFairy" "Creative Cloud" "Arc" "Brave Browser" "Safari Technology Preview" "YouTube" "SiriusXM" "Xcode.app" ".Xcode-beta" "Simulator" "Podcasts" "Microsoft Remote Desktop" "zen" "RustDesk")
#prg=( "Safari Technology Preview" )
killprg=( "runningboardd" "Brave Browser" "Microsoft Edge" )
for app in "${prg[@]}"
do
  if [[ $app = .* ]]
  then
    skip="x"
  else
    # echo $'\t' "$app"
    # timestamp
    ts=`date +%T`
  
    #echo "$ts: begin checking..."
    AID=$(ps -ef | grep "${app}" | grep -v `basename $0` | grep -v "grep" | wc -l)
    #[[ $AID -eq 0 ]] && echo "$ts: $app not running"

    if [[ $AID -gt 0 ]]
    then
      RS=$(osascript ${SCRIPT_DIR}/quit-app.app "$app")
      echo $'\t' ${RS}
      if [[ $RS == *"QUIT"* ]]; then
        killprg+=("${app}")
        sleep 1
      fi
    fi
   fi
done


echo -e "\n\n\n"
echo "** Pause 10 secs **"


sleep 10
echo -e "\n\n\n"
echo "** Force Quit (kill) Backup and Background Apps **"
killcnt=${#killprg[@]}
echo "...kill count: ${killcnt}"
if [[ $killcnt -gt 0 ]]
then
  for app in "${killprg[@]}"
  do
    if [[ $app = .* ]]
    then
      sleep 1
    else
      echo $'\t' "$app"
      killall "${app}"
      sleep 1
    fi
  done
fi

#echo -e "\n\n\n"
#echo "** pmset -g everything **"
#echo "pmset -g everything"
#/usr/bin/pmset -g everything

# sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool true
# sudo pmset disksleep 0
# sudo pmset womp 0
# sudo pmset powernap 0
# sudo pmset ttyskeepawake 0
# sudo pmset tcpkeepalive 1
# sudo pmset schedule cancelall
# sudo pmset repeat cancel
# sudo chflags schg /Library/Preferences/SystemConfiguration/com.apple.AutoWake.plist
# sudo mkdir -p /Library/Preferences/FeatureFlags/Domain
# sudo cp /System/Library/FeatureFlags/Domain/powerd.plist /Library/Preferences/FeatureFlags/Domain
# sudo nano /Library/Preferences/FeatureFlags/Domain/powerd.plist
# replace <true/> to <false/>
# reboot

# Make sure AutoWake file is not writeable
# sudo chflags schg /Library/Preferences/SystemConfiguration/com.apple.AutoWake.plist

echo -e "\n\n\n"
echo "** Adjust Sleep Settings to Avoid Wakes **"
echo "* pmset settings"
echo "sudo -S pmset schedule cancelall"
# more /etc/sudoers.d/shughey
# shughey ALL=(ALL) NOPASSWD: /usr/bin/pmset
sudo -S pmset schedule cancelall
sudo pmset repeat cancel
# echo "sudo pmset -a hibernatemode 0"
# sudo pmset -a hibernatemode 0
echo "sudo pmset -a autopoweroff 0"
sudo pmset -a autopoweroff 0
echo "sudo pmset -a standby 0"
sudo pmset -a standby 0
#echo "sudo pmset -a tcpkeepalive 0"
# trying to get back MultiCast - 23-Mar-2025
echo "sudo pmset -a tcpkeepalive 0"
sudo pmset -a tcpkeepalive 0
echo "sudo pmset -a powernap 0"
sudo pmset -a powernap 0

# trying to get back MultiCast - 23-Mar-2025


#echo "sudo pmset -a tcpkeepalive 1"
#sudo pmset -a tcpkeepalive 1
#sudo pmset disksleep 30
# must add defaults to sudoers.d
#sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool false
# export MACHINE=Angus; dns-sd -R ${MACHINE}.local _device-info._tcp local 0
# dns-sd -q ${MACHINE}.local
 