#!/bin/bash

OUTPUT='/tmp/statusmail.txt'
SDATE=`date +"%l:%M %p" | tr '[:upper:]' '[:lower:]'`
START="$(date +%s)"
FULLDATE="$(date)"
ESUBJ="${KMINFO_MacroName} @ ${SDATE}"
export ESUBJ
cname=`scutil --get ComputerName`
script=`basename $0`
dnqf=/tmp/caffeinate-do-not-quit.txt

echo "// idlecheck" > ${OUTPUT}
echo "  " `date` >> ${OUTPUT}
echo "   machine: ${cname}" >> ${OUTPUT}
echo "   script: ${script}" >> ${OUTPUT}
echo "  " `/usr/bin/sw_vers` >> ${OUTPUT}
echo "  " `sysctl kern.version` >> ${OUTPUT}
echo "  " `sysctl kern.ostype` >> ${OUTPUT}
echo "  " `sysctl kern.osrelease` >> ${OUTPUT}
echo "  " `sysctl kern.osrevision` >> ${OUTPUT}
echo "" >> ${OUTPUT}

/bin/bash ${HOME}/Dropbox/bin/idlecheck_caffeinatestuck >> ${OUTPUT}
caffeinates=`cat ${dnqf} | wc -l`
#echo ${dnqf}
#echo ${caffeinates}
#exit

echo "" >> ${OUTPUT}
echo "" >> ${OUTPUT}
echo "" >> ${OUTPUT}
if [[ ${caffeinates} -gt 0 ]]; then
  echo " █████                                  " >> ${OUTPUT}
  echo "░░███                                   " >> ${OUTPUT}
  echo " ░███████  █████ ████  █████  █████ ████" >> ${OUTPUT}
  echo " ░███░░███░░███ ░███  ███░░  ░░███ ░███ " >> ${OUTPUT}
  echo " ░███ ░███ ░███ ░███ ░░█████  ░███ ░███ " >> ${OUTPUT}
  echo " ░███ ░███ ░███ ░███  ░░░░███ ░███ ░███ " >> ${OUTPUT}
  echo " ████████  ░░████████ ██████  ░░███████ " >> ${OUTPUT}
  echo "░░░░░░░░    ░░░░░░░░ ░░░░░░    ░░░░░███ " >> ${OUTPUT}
  echo "                               ███ ░███ " >> ${OUTPUT}
  echo "                              ░░██████  " >> ${OUTPUT}
  echo "                               ░░░░░░   " >> ${OUTPUT}
  ESUBJ="can't sleep, busy @ ${SDATE}"
  export ESUBJ
  echo "" >> ${OUTPUT}
  echo "// some processes preventing sleep:" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  cat ${dnqf} >> ${OUTPUT}
  /usr/bin/python3 /Users/shughey/Dropbox/bin/send_status_mail3.py
else
  echo "         ████                              ███" >> ${OUTPUT}
  echo "        ░░███                             ░███" >> ${OUTPUT}
  echo "  █████  ░███   ██████   ██████  ████████ ░███" >> ${OUTPUT}
  echo " ███░░   ░███  ███░░███ ███░░███░░███░░███░███" >> ${OUTPUT}
  echo "░░█████  ░███ ░███████ ░███████  ░███ ░███░███" >> ${OUTPUT}
  echo " ░░░░███ ░███ ░███░░░  ░███░░░   ░███ ░███░░░ " >> ${OUTPUT}
  echo " ██████  █████░░██████ ░░██████  ░███████  ███" >> ${OUTPUT}
  echo "░░░░░░  ░░░░░  ░░░░░░   ░░░░░░   ░███░░░  ░░░ " >> ${OUTPUT}
  echo "                                 ░███         " >> ${OUTPUT}
  echo "                                 █████        " >> ${OUTPUT}
  echo "                                ░░░░░         " >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  echo "// sleep at ${FULLDATE}" >> ${OUTPUT}
  /usr/bin/python3 /Users/shughey/Dropbox/bin/send_status_mail3.py
  DURATION=$[ $(date +%s) - ${START} ]
  #cat /tmp/wakemaints.txt | fgrep "Wake reason"
  rm ${OUTPUT}
  sleep 15
  # Sleep now
  /usr/bin/pmset sleepnow
fi

