#!/bin/bash
# Copyright 2017 Lucid Networks sloeckle
# Package Version 1.11-2 - Script Version 11

. /opt/nexp-tools/nexp-tools.lib

if [ -a /home/nexp/bin/disable-second-monitor.sh ]; then
  /home/nexp/bin/disable-second-monitor.sh
  sleep 5
fi

source /etc/nexp-tools/nexp-tools.conf
export DISPLAY=:0
export EMAIL=$HOSTNAME'@lucidnetworks.net'
currentresolution=$(xdpyinfo | grep dimensions: | awk '{print $2}')
if [[ $currentresolution == *"3840x2160"* ]]
then
  background="nexp3840x2160.jpg"
else
  background="nexp1920x1080.jpg"
fi
time=$(date +"%m-%d-%Y_%T")
rand=$(od -N 4 -t uL -An /dev/urandom | tr -d " ")
dir=/tmp/$rand
mkdir $dir &>/dev/null
systeminfo
echo "Shutting down Chrome"
killproc chrome &>/dev/null
sleep 5

echo "Clearing cache"
rm -rf /home/nexp/.cache/google-chrome/*
rm -rf /home/nexp/.config/google-chrome/Default/Web\ Data
echo "Starting up Chrome"
if [[ $1 == "-notfullscreen" ]]
then
  /usr/bin/google-chrome --extensions-update-frequency=5 file:///usr/share/nexp-tools/$background &
else
  /usr/bin/google-chrome $CHROMEOPTS file:///usr/share/nexp-tools/$background &
fi
sleep 2
xdotool key F5
sleep 1
xdotool key space
secs=10
while [ $secs -gt 0 ]; do
   echo -ne "Waiting for $secs\033[0K seconds\r"
   sleep 1
   : $((secs--))
done
echo "Gathering screenshot data"
scrot $dir/$time.png &>/dev/null
convert $dir/$time.png -colorspace Gray $dir/$time.tif
ocr=$(tesseract $dir/$time.tif stdout)
text="$ocr\n\n\n$systeminfo\n"
echo "Sending notifications"
if [ $APPNOTIFICATION == true ]; then
  echo -e $text | mutt -s "$HOSTNAME Chrome restart script run!" -a $dir/$time.png -- $APPMAILTO
fi
rm -rf $dir &>/dev/null
echo "All done"
