#!/bin/bash

OUTPUT='/tmp/statusmail.txt'
OUTPUT2='/tmp/maintwakes.txt'
TIMEINT='3h'
PMLOG_LMT='50'
START="$(date +%s)"
ESUBJ="$KMINFO_MacroName"
export ESUBJ
script=`basename $0`

cname=`scutil --get ComputerName`

echo "// wake! maintenance/DarkWake report" > ${OUTPUT}
echo "  " `date` >> ${OUTPUT}
echo "   Machine: ${cname}" >> ${OUTPUT}
echo "   Script: " `basename $0` >> ${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}
echo "" >> ${OUTPUT}
echo "" >> ${OUTPUT}
echo "                       █████               ███" >> ${OUTPUT}
echo "                      ░░███               ░███" >> ${OUTPUT}
echo " █████ ███ ███████████ ░███ █████  ██████ ░███" >> ${OUTPUT}
echo "░░███ ░███░░███░░░░░███░███░░███  ███░░███░███" >> ${OUTPUT}
echo " ░███ ░███ ░███ ███████░██████░  ░███████ ░███" >> ${OUTPUT}
echo " ░░███████████ ███░░███░███░░███ ░███░░░  ░░░ " >> ${OUTPUT}
echo "  ░░████░████ ░░███████████ █████░░██████  ███" >> ${OUTPUT}
echo "   ░░░░ ░░░░   ░░░░░░░░░░░ ░░░░░  ░░░░░░  ░░░ " >> ${OUTPUT}

echo "Scanning log for maintenance wakes..."
log show --style syslog --last ${TIMEINT} | fgrep "Wake reason" | fgrep "Maintenance" | tail -r >> ${OUTPUT2}
lines=`cat ${OUTPUT2} | grep -c '^'`
DURATION=$[ $(date +%s) - ${START} ]
if [ "$lines" -gt 1 ]
then
  echo "Maintenance Wakes // ---------------------------------------------" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  echo "Occurances: $lines" >> ${OUTPUT}
  echo "Duration: ${DURATION}" >> ${OUTPUT}
  echo "Look Back Time Interval: ${TIMEINT}" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  cat ${OUTPUT2} >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  echo "------------------------------------------------------------------" >> ${OUTPUT}
  #echo "$ott" > /tmp/wakemaints.txt
else
  echo "No maintenance wakes last ${TIMEINT}"
fi

echo "Scanning for DarkWake..."
pmset -g log | fgrep "DarkWake" | tail -r -n ${PMLOG_LMT} >> ${OUTPUT2}
lines2=`cat ${OUTPUT2} | grep -c '^'`
if [ "$lines2" -gt 1 ]
then
  echo "" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  if [ "$lines" -gt 1 ]; then
    echo "" >> ${OUTPUT}
  fi

  echo "DarkWakes // -----------------------------------------------------" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  echo "Occurances: $lines2" >> ${OUTPUT}
  echo "Look Back Line Limit: ${PMLOG_LMT}" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  cat ${OUTPUT2} >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  echo "" >> ${OUTPUT}
  echo "------------------------------------------------------------------" >> ${OUTPUT}
  #echo "$ott" > /tmp/wakemaints.txt
else
  echo "No DarkWakes last ${PMLOG_LMT} lines (pmset -g log)"
fi

if [[ "$lines" -gt 1 || "$lines2" -gt 1 ]]
then
  /usr/bin/python3 $HOME/Dropbox/bin/send_status_mail3.py
fi

#cat /tmp/wakemaints.txt | fgrep "Wake reason"
rm ${OUTPUT}
rm ${OUTPUT2}
