#!/bin/bash

CONFIG="/opt/pos/etc/config.ini"
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=`

DEVICE=`xrandr | grep "connected" | grep -v disconnected | head -1`
RESOLUTION=`echo "$DEVICE" | perl -wne 'print "$1 $2" if /\s(\d+)x(\d+)\+/'`

W=800
H=600

if [ "$RESOLUTION" != "" ]; then
  W=`echo $RESOLUTION | cut -d" " -f1`
  H=`echo $RESOLUTION | cut -d" " -f2`
fi

# kill x11vnc if its running
ps xa | grep x11vnc | grep -v grep | awk '{ print $1 }' | xargs kill -9 2> /dev/null

VNC_PASSWD=`cat /opt/pos/etc/config.ini | grep "VNC_PASSWD=" | grep -v "#" | cut -f2 -d"="`

if [ "$VNC_PASSWD" != "" ]; then
  VNC_PASSWD="-passwd $VNC_PASSWD"
fi

while [ true ]; do
  #if [ "$SCREEN_RESCALE_W" != "" ] && [ "$SCREEN_RESCALE_H" != "" ] && [ "$SCREEN_RESCALE_W" != "0" ] && [ "$SCREEN_RESCALE_H" != "0" ]; then
  #  /usr/bin/x11vnc $VNC_PASSWD -notruecolor -norc -forever -scale ${SCREEN_RESCALE_W}x${SCREEN_RESCALE_H} -geometry ${SCREEN_RESCALE_W}x${SCREEN_RESCALE_H} -display :0 -shared
  #else
  #  /usr/bin/x11vnc $VNC_PASSWD -notruecolor -norc -forever -scale 800x600 -geometry 800x600 -display :0 -shared
  #fi

  /usr/bin/x11vnc $VNC_PASSWD -notruecolor -norc -forever -scale 800x600 -geometry ${W}x${H} -display :0 -shared

  sleep 1
done
