#!/bin/bash

CONFIG="/opt/pos/etc/config.ini"
STATION_NUMBER=`cat /opt/pos/etc/config.ini | grep STATION_NUMBER | cut -f2 -d=`
X64_ACTIVE=`cat $CONFIG | grep "X64_ACTIVE" | cut -f2 -d=`
KILLED=0
#HAS_MOBILE_DEVICES=`cat $CONFIG | grep MOBILE_DEVICES | grep -v grep | grep 1`

if [ "$X64_ACTIVE" = "1" ]; then
  for pid in `ps xa | grep "x64\.gambas" | grep -v grep | awk '{print $1;}'`; do
    kill -9 $pid 2> /dev/null
  done
fi

#if [ "$HAS_MOBILE_DEVICES" != "" ]; then
#  if [ ! -e "/usr/bin/starman" ]; then
#    # restart mobile if it's running
#    MOBILE_PID=`ps -eo pid,args | grep perl | grep mobile  | grep -v grep | cut -c1-6`
#
#    if [ "$MOBILE_PID" != "" ]; then
#      kill -9 $MOBILE_PID 2> /dev/null
#      /opt/pos/common/addons/mobile/bin/app.pl --daemon
#    fi
#  else
#    /opt/pos/common/bin/mobile_devices.sh &
#  fi
#fi

if [ "$STATION_NUMBER" = "0" ]; then
  rm -rf /opt/pos/server/data/registered_printers/*

  # only clean registered stations which are not nomachines
  for station in `ls /opt/pos/server/data/registered_stations/* 2> /dev/null`; do
    st=`echo $station | cut -f7 -d/`

    if [ $st -lt 81 ]; then
      rm -f $station
    fi
  done
fi

if [ -d "/opt/logs" ] && [ ! -L "/root/logs" ]; then
  rm -rf /root/logs
  ln -s /opt/logs /root/logs
fi

if [ -d "/opt/logs" ] && [ ! -L "/home/pos/logs" ]; then
  rm -rf /home/pos/logs
  ln -s /opt/logs /home/pos/logs
fi

# restart customer display app
ps xa | grep addons/graphical_display | grep app | grep -v grep | awk '{ print $1 }' | xargs kill -9 2> /dev/null

# kill and start handlers
ps xa | grep devices_handler | grep -v grep | awk '{ print $1 }' | xargs kill -9 2> /dev/null
ps xa | grep Proc::Launcher | grep -v grep | awk '{ print $1 }' | xargs kill -9 2> /dev/null

/opt/pos/common/bin/devices_handler.pl &

