#!/bin/bash

export DISPLAY=:0.0

BIN=""

if [ -e "/usr/bin/teamviewer7" ]; then
  BIN="/usr/bin/teamviewer7"
elif [ -e "/usr/bin/teamviewer" ]; then
  BIN="/usr/bin/teamviewer"
else
  xmessage -timeout 10 "Can't find teamviewer..."
  exit
fi

if [ -e "/etc/systemd/system/teamviewerd.service" ]; then
  if [ ! -e "/etc/systemd/system/multi-user.target.wants/teamviewerd.service" ]; then
    systemctl enable teamviewerd
  fi

  systemctl start teamviewerd
fi

tib=`cat /tib_version | cut -f1 -d_`

FOREVER=$1

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

  if [ "$tib" -ge "201708" ]; then
    su - pos -c $BIN
  else
    $BIN
  fi

else
  while [ 1 ]; do
    for pid in `ps xa | grep TeamViewer\.exe | grep -v grep | awk '{print $1}'`; do
      kill -9 $pid 2> /dev/null
    done

    sleep 3

    if [ "$tib" -ge "201708" ]; then
      su - pos -c $BIN
    else
      $BIN
    fi

  done
fi

