#!/bin/bash

export DISPLAY=:0.0

ERRORS_SCREENSHOTS="/opt/pos/etc/errors_screenshots"

if [ ! -d "$ERRORS_SCREENSHOTS" ]; then
  mkdir -p $ERRORS_SCREENSHOTS
else
  count=0

  for file in `ls -tra $ERRORS_SCREENSHOTS/*.jpg | sort -r`; do

    if [ $count -gt 10 ]; then
      echo "will delete $file - $count"
      rm -f $file
    fi

    count=`expr $count + 1`
  done
fi

DO_CMD=0
APPEARED=0

while [ true ]; do
  # check ative workspace
  #ACTIVE_WORKSPACE=`wmctrl -d | grep "*" | awk '{ print $1 }'`

  #if [ $ACTIVE_WORKSPACE -ne 0 ]; then
  #  wmctrl -s 0
  #fi

  ERROR=`wmctrl -l | grep -i "pos pos"`

  #echo "###1 APPEARED: $APPEARED, DO_CMD: $DO_CMD"

  if [ "$ERROR" != "" ] && [ "$APPEARED" == "0" ] && [ $DO_CMD == "0" ]; then
    TMP_DATE=`date +%Y%m%d_%H%M%S`
    echo "$TMP_DATE" >> $ERRORS_SCREENSHOTS/errors.txt
    APPEARED="1"
    DO_CMD="1"
  elif [ "$ERROR" == "" ]; then
    APPEARED="0"
    DO_CMD="0"
  fi

  if [ "$APPEARED" == "1" ] && [ $DO_CMD == "1" ]; then
    #echo "VOU EXECUTAR"
    wmctrl -r pos -b toggle,above

    TMP_DATE=`date +%Y%m%d_%H%M%S`
    import -window root $ERRORS_SCREENSHOTS/${TMP_DATE}.jpg

    DO_CMD="0"
  fi

  sleep 5
done


