#!/bin/bash

COUNT=0
BAD=0
CPU_LIMIT=80
HDD_CHECK_COUNT=20
DID_RESTART=0

export DISPLAY=:0.0

LOG_FILENAME=/root/logs/cpu_load_monitor_log.log
GB_FILE_TIME=`stat -c %Y /opt/pos/common/bin/pos`
WATCHDOG_PORT=`cat /opt/pos/etc/config.ini | grep WATCHDOG_PORT | cut -f2 -d=`
DISABLE_CPU_MONITOR=`cat /opt/pos/etc/config.ini | grep DISABLE_CPU_MONITOR | cut -f2 -d=`

while [ 1 ]; do

  if [ ! -d "/root/logs" ]; then
    sleep 5
    continue
  fi

  CUR_DATE=`date +%Y%m%d_%H%M%S`
  DEVICES_RUNNING=`ps xa | grep devices_handler | grep -v grep`
  GB_PID=`ps xa | grep common/bin/pos | grep -v grep | grep -v sudo | awk '{ print $1 }'`

  if [ "$DEVICES_RUNNING" = "" ]; then
    echo "[$CUR_DATE] devices_handler is stopped, will start it..." >> $LOG_FILENAME
    /opt/pos/common/bin/devices_handler.pl &
  fi

  X_RUNNING=`ps xa | grep X | grep nolisten`

  #
  # check hdd disk space
  #

  if [ "$X_RUNNING" != "" ]; then

    # main loop sleeps 15 secs, these are 20 iterations, which are 5 mins
    if [ $HDD_CHECK_COUNT -eq 20 ]; then
      HDD_BUSY=`df -l | head -2 | tail -1 | awk '{ print $5 }' | sed 's/%//'`

      # hdd is more than 90% busy
      if [ $HDD_BUSY -gt 90 ]; then
        echo "#ALERT#ATENÇÃO!<BR>ESPAÇO EM DISCO A TERMINAR<BR>CONTACTAR TÉCNICO" | nc -w1 127.0.0.1 8088
      fi

      HDD_CHECK_COUNT=0
    fi

    HDD_CHECK_COUNT=`expr $HDD_CHECK_COUNT + 1`
  fi

  #
  # watchdog handling
  #

  if [ "$WATCHDOG_PORT" != "" ]; then
    RES=`statserial -n $WATCHDOG_PORT > /tmp/watchdog_port.txt`
    cat /tmp/watchdog_port.txt | grep CTS > /tmp/watchdog_port2.txt
    RES=`cat /tmp/watchdog_port2.txt | grep 34H1`

    if [ "$RES" = "" ]; then
      echo "[$CUR_DATE] WATCHDOG - BUTTON TRIGGERED" >> /root/logs/watchdog.log


      if [ "$X_RUNNING" = "" ]; then
        echo "[$CUR_DATE] WATCHDOG - WILL CHECK DISK AND REBOOT" >> /root/logs/watchdog.log
        chkdsk
        reboot
      else
        echo "[$CUR_DATE] WATCHDOG - WILL KILL APP" >> /root/logs/watchdog.log
        kill -9 $GB_PID 2> /dev/null
      fi
    fi
  fi

  # monitor server
  STATION_NUMBER=`cat /opt/pos/etc/config.ini | grep STATION_NUMBER | cut -f2 -d=`

  # station monitor
  if [ "$STATION_NUMBER" != "0" ]; then
    FILES=""

    if [ -e "/usr/bin/timeout" ]; then
      FILES=`timeout 3 ls /shares/pos/etc 2> /dev/null`
    else
      FILES=`ls /shares/pos/etc 2> /dev/null`
    fi

    COOL=1

    # server is not mounted...
    if [ "$FILES" = "" ]; then
      COOL=0
      kill -9 $GB_PID 2> /dev/null
      echo "[$CUR_DATE] Server FILES error..." >> $LOG_FILENAME
      touch /tmp/server_error.txt

      if [ "$X_RUNNING" != "" ]; then
        xmessage -buttons ConfigEdit:2,Reboot:3,Retry:4 -timeout 10 "SERVER FILES ACCESS ERROR..."
        XRES="$?"

        if [ $XRES -eq 1 ]; then
          #perl -pi -e "s/STATION_NUMBER=\d+/STATION_NUMBER=0/" /opt/pos/etc/config.ini
          reboot
        elif [ $XRES -eq 2 ]; then
          if [ -e "/opt/bin/keyboard.sh" ]; then
            /opt/bin/keyboard.sh
          else
            /usr/bin/matchbox-keyboard &
          fi

          xterm -e nano /opt/pos/etc/config.ini

          if [ -e "/opt/bin/keyboard.sh" ]; then
            /opt/bin/keyboard.sh 1
          else
            killall -9 matchbox-keyboard
          fi
        elif [ $XRES -eq 3 ]; then
          /sbin/reboot
        elif [ $XRES -eq 4 ]; then
          /opt/pos/common/bin/restart_hardware_handler.sh
        else
          /opt/pos/common/bin/restart_hardware_handler.sh
        fi
      fi
    else
      if [ -e "/tmp/server_error.txt" ]; then
        rm -rf /tmp/server_error.txt
        /opt/pos/common/bin/restart_hardware_handler.sh
      fi
    fi

    if [ -e "/tmp/server_db_error.txt" ]; then
      COOL=0
      kill -9 $GB_PID 2> /dev/null
      echo "[$CUR_DATE] Server DB error..." >> $LOG_FILENAME

      if [ "$X_RUNNING" != "" ]; then
        FREE_HDD_SPACE=`df -l | head -2 | tail -1 | awk '{ print $5 }' | sed 's/%//'`

        if [ $FREE_HDD_SPACE -gt 95 ]; then
          xmessage -center -timeout 5 "HDD PROBLEM: $FREE_HDD_SPACE% USED"
        fi

        xmessage -buttons ConfigEdit:2,Reboot:3,Retry:4 -timeout 10 "SERVER DATABASE ACCESS ERROR..."
        XRES="$?"

        if [ $XRES -eq 1 ]; then
          #perl -pi -e "s/STATION_NUMBER=\d+/STATION_NUMBER=0/" /opt/pos/etc/config.ini
          reboot
        elif [ $XRES -eq 2 ]; then
          if [ -e "/opt/bin/keyboard.sh" ]; then
            /opt/bin/keyboard.sh
          else
            /usr/bin/matchbox-keyboard &
          fi
          xterm -e nano /opt/pos/etc/config.ini

          if [ -e "/opt/bin/keyboard.sh" ]; then
            /opt/bin/keyboard.sh 1
          else
            killall -9 matchbox-keyboard
          fi
        elif [ $XRES -eq 3 ]; then
          /sbin/reboot
        elif [ $XRES -eq 4 ]; then
          /opt/pos/common/bin/restart_hardware_handler.sh
        else
          /opt/pos/common/bin/restart_hardware_handler.sh
        fi
      fi
    else
      if [ -e "/tmp/server_db_error.txt" ]; then
        rm -rf /tmp/server_db_error.txt
        /opt/pos/common/bin/restart_hardware_handler.sh
      fi
    fi

    #if [ $COOL -eq 1 ]; then
    #  echo "Server is cool..."
    #fi
  # server machine
  else
    if [ -e "/tmp/server_db_error.txt" ]; then
      kill -9 $GB_PID 2> /dev/null
      echo "Server DB error..." >> $LOG_FILENAME

      if [ "$X_RUNNING" != "" ]; then
        FREE_HDD_SPACE=`df -l | head -2 | tail -1 | awk '{ print $5 }' | sed 's/%//'`

        if [ $FREE_HDD_SPACE -gt 95 ]; then
          xmessage -center -timeout 5 "HDD PROBLEM: $FREE_HDD_SPACE% USED"
        fi

        xmessage -buttons ConfigEdit:2,Reboot:3,Retry:4 -timeout 10 "SERVER DATABASE ACCESS ERROR..."
        XRES="$?"

        if [ $XRES -eq 1 ]; then
          #perl -pi -e "s/STATION_NUMBER=\d+/STATION_NUMBER=0/" /opt/pos/etc/config.ini
          reboot
        elif [ $XRES -eq 2 ]; then
          if [ -e "/opt/bin/keyboard.sh" ]; then
            /opt/bin/keyboard.sh
          else
            /usr/bin/matchbox-keyboard &
          fi
          xterm -e nano /opt/pos/etc/config.ini

          if [ -e "/opt/bin/keyboard.sh" ]; then
            /opt/bin/keyboard.sh 1
          else
            killall -9 matchbox-keyboard
          fi
        elif [ $XRES -eq 3 ]; then
          /sbin/reboot
        elif [ $XRES -eq 4 ]; then
          /opt/pos/common/bin/restart_hardware_handler.sh
        else
          /opt/pos/common/bin/restart_hardware_handler.sh
        fi
      fi
    else
      if [ -e "/tmp/server_db_error.txt" ]; then
        rm -rf /tmp/server_db_error.txt
        /opt/pos/common/bin/restart_hardware_handler.sh
      fi

      #echo "Database is cool..."
    fi
  fi

  LOG_FILESIZE=0

  if [ -e $LOG_FILENAME ]; then
    LOG_FILESIZE=$(stat -c%s "$LOG_FILENAME")
  fi

  # log cleanup
  if [ $LOG_FILESIZE -gt 100000 ]; then
    echo "refresh" > $LOG_FILENAME
  fi

  echo "[$CUR_DATE] Loop COUNT=$COUNT, LOG_FILESIZE=$LOG_FILESIZE" >> $LOG_FILENAME

  GB_FILE_TIME_NOW=`stat -c %Y /opt/pos/common/bin/pos`

  if [ $DID_RESTART -eq 1 ]; then
    DID_RESTART=0
    GB_FILE_TIME=$GB_FILE_TIME_NOW
  else
    if [ "$GB_FILE_TIME" != "$GB_FILE_TIME_NOW" ]; then
      GB_FILE_TIME=$GB_FILE_TIME_NOW
      kill -9 $GB_PID 2> /dev/null
      DID_RESTART=1
    fi
  fi

  sleep 15
done

