#!/bin/bash
#
# /etc/init.d/teamviewerd
#
# chkconfig: 2345 95 05
# description: daemon for TeamViewer
#
# processname: teamviewerd
# config: /etc/teamviewer/global.conf
# pidfile: /var/run/teamviewerd.pid

### BEGIN INIT INFO
# Provides:          teamviewerd
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Required-Start:    $all
# Required-Stop:     $local_fs $network $named
# Short-Description: TeamViewer remote control daemon
# Description:       TeamViewer remote control daemon
### END INIT INFO

RETVAL=0
prog="teamviewerd"
prog_dir="/opt/teamviewer/tv_bin"
prog_path="$prog_dir/$prog"
prog_args="-d"
pidfile="/var/run/teamviewerd.pid"

lockdir='/var/lock/subsys'
[ -d $lockdir ] || lockdir='/var/lock'
lockfile=$lockdir/$prog

function Main()
{

  case "$1" in
    start)	start	;;
    stop)	stop	;;
    restart)	restart	;;
    reload)	restart	;;
    status)	status	;;
    *)		helpmsg	;;
  esac

  exit $RETVAL
}

function start()
{
  echo -n $"Starting $prog..."

  $prog_dir/script/tv-delayed-start.sh

  $prog_path $prog_args

  RETVAL=$?
  [ "$RETVAL" = 0 ] && touch $lockfile
  echo
}

function stop()
{
  echo -n $"Stopping $prog... "

  killDaemon
  RETVAL=$?
  [ "$RETVAL" = 0 ] && rm -f $lockfile
  echo
}

function restart()
{
  stop
  [ "$RETVAL" = 0 ] || return
  start
}

function status()
{
  RETVAL=0

  isRunning && echo "$prog start/running" && return

  echo "$prog stop/waiting"
}

function helpmsg()
{
  echo $"Usage: $0 {start|stop|restart|status}"
  RETVAL=1
}

function isRunning()
{
  local pid=$(getPID)
  [ -n "$pid" ] || return
  
  readlink /proc/$pid/exe | grep -q $prog
}

function getPID()
{
  cat $pidfile 2> /dev/null
}

function killDaemon()
{
  cmdExists killproc && killproc $prog_path && return

  isRunning || echo not running
  isRunning || return 0
  
  local repeat=30
  local pid=$(getPID)
  [ -n "$pid" ] || return

  kill -TERM $pid 2> /dev/null

  until [ $repeat = 0 ]; do
    isRunning || break
    echo -n '. '
    sleep 0.33
    let repeat-=1
  done

  isRunning || return 0
  kill -KILL $pid 2> /dev/null
}

function cmdExists()
{
  command -v "$1" >/dev/null 2>&1
}

Main "$@"
