#!/bin/bash

export DISPLAY=:0.0

if [ ! -e "/usr/bin/anydesk" ]; then
  xmessage -timeout 10 "Can't find /usr/bin/anydesk"
  exit
fi

if [ -d "/home/pos/.anydesk" ]; then
  chown pos:pos -R /home/pos/.anydesk
  chown pos:pos -R /home/pos/.anydesk/*
fi

if [ -e "/home/pos/.anydesk/anydesk.log" ]; then
  rm -f /home/pos/.anydesk/anydesk.log
fi

FOREVER=$1

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

  sudo -u pos /usr/bin/anydesk &
  sleep 3
  wmctrl -r anydesk -e 0,10,10,400,400
else
  while [ 1 ]; do
    RUNNING=`ps xa | grep /usr/bin/anydesk | grep -v grep`

    if [ "$RUNNING" = "" ]; then
      sudo -u pos /usr/bin/anydesk &
      sleep 3
      wmctrl -r anydesk -e 0,10,10,400,400
    fi

    sleep 10
  done
fi

