#!/bin/bash

CONFIG="/opt/pos/etc/config.ini"

while [ 1 ]; do
  USE_V2=`cat $CONFIG | grep "GRAPHICAL_DISPLAY_USE_V2=" | grep -v grep | cut -f2 -d=`

  # graphical display - v2
  if [ "$USE_V2" = "1" ] && [ -d "/opt/pos/common/addons/graphical_display_v2" ]; then
    ps xa | grep addons/graphical_display | grep app | grep -v grep | awk '{ print $1 }' | xargs kill -9 2> /dev/null

    DEVICE_MAIN=`/opt/bin/xrandr_devices | head -1`
    DEVICE_DISPLAY=`/opt/bin/xrandr_devices | tail -1`

    if [ "$DEVICE_DISPLAY" != "$DEVICE_MAIN" ]; then
      DEVICE_MAIN_W=`/opt/bin/xrandr_devices | head -1 | cut -d, -f2 | cut -f1 -dx`
      DEVICE_DISPLAY_W=`/opt/bin/xrandr_devices | tail -1 | cut -d, -f2 | cut -f1 -dx`
      DEVICE_DISPLAY_H=`/opt/bin/xrandr_devices | tail -1 | cut -d, -f2 | cut -f2 -dx`
      FONT_SIZE=`cat $CONFIG | grep "GRAPHICAL_DISPLAY_V2_FONTSIZE=" | grep -v grep | cut -f2 -d=`
      MARGIN_TOP=`cat $CONFIG | grep "GRAPHICAL_DISPLAY_V2_TOP_MARGIN=" | grep -v grep | cut -f2 -d=`
      MARGIN_RIGHT=`cat $CONFIG | grep "GRAPHICAL_DISPLAY_V2_RIGHT_MARGIN=" | grep -v grep | cut -f2 -d=`
      AUTO_RELOCATE_WINDOWS=`cat $CONFIG | grep "AUTO_RELOCATE_WINDOWS=" | grep -v grep | cut -f2 -d=`

      if [ "$AUTO_RELOCATE_WINDOWS" = "1" ]; then
        # if relocate windows is running, restart it
        RELOCATE_WINDOWS_RUNNING=`ps xa | grep relocate_windows | grep -v grep`

        if [ "$RELOCATE_WINDOWS_RUNNING" = "" ]; then
          SCREEN_RESCALE_W=`cat $CONFIG | grep SCREEN_RESCALE_W | grep -v grep | cut -f2 -d=`
          SCREEN_RESCALE_H=`cat $CONFIG | grep SCREEN_RESCALE_H | grep -v grep | cut -f2 -d=`

          if [ "$SCREEN_RESCALE_W" != "" ] && [ "$SCREEN_RESCALE_H" != "" ]; then
            /opt/pos/common/bin/relocate_windows $SCREEN_RESCALE_W $SCREEN_RESCALE_H &
          else
            /opt/pos/common/bin/relocate_windows &
          fi
        fi
      fi

      if [ "$FONT_SIZE" = "" ]; then
        FONT_SIZE="1"
      fi

      if [ "$MARGIN_TOP" = "" ]; then
        MARGIN_TOP="0"
      fi

      if [ "$MARGIN_RIGHT" = "" ]; then
        MARGIN_RIGHT="0"
      fi

      if [ "$DEVICE_MAIN_W" != "" ] && [ "" != "$DEVICE_DISPLAY_W" ] && [ "$DEVICE_DISPLAY_H" != "" ]; then
        /opt/pos/common/addons/graphical_display_v2/app $DEVICE_MAIN_W 10 $DEVICE_DISPLAY_W $DEVICE_DISPLAY_H $FONT_SIZE $MARGIN_RIGHT $MARGIN_TOP
      fi
    fi

  # graphical display - v1
  else
    ps xa | grep addons/graphical_display/app | grep -v grep | awk '{ print $1 }' | xargs kill -9 2> /dev/null
    rm -rf /opt/pos/common/tmp/graphical_display 2> /dev/null

    if [ ! -d "/opt/pos/common/tmp/graphical_display" ]; then
      mkdir /opt/pos/common/tmp/graphical_display
    fi

    /opt/pos/common/addons/graphical_display/app
  fi

  sleep 2
done

