#!/bin/bash

source "$TV_SCRIPT_DIR/tvw_aux"
source "$TV_SCRIPT_DIR/tvw_config"
source "$TV_SCRIPT_DIR/tvw_exec"
source "$TV_SCRIPT_DIR/tvw_extra"
source "$TV_SCRIPT_DIR/tvw_daemon"
source "$TV_SCRIPT_DIR/tvw_profile"

function Main()
{
  local param="$1"
  local opt="$2"
  
  echo
  
  case "$param" in
    --help )			PrintHelp				;;
    --version )			PrintVersion			;;
    --info )			PrintInfo				;;
    --daemon )			Run_Daemon $opt			;;
    --winecfg )	shift;	Run_WineCfg "$@"		;;
    --regedit )	shift;	Run_RegEdit "$@"		;;
    --kill )			Run_KillTeamViewer		;;
    --update-profile )	Init					;;
    --ziplog )			CreateZipLog			;;
    -ziplog )			CreateZipLog			;;
    --passwd )			SetPasswd "$opt"		;;
    --export-license )	ExportLicense "$opt"	;;
    * )					Run_TeamViewer "$@"		;;
  esac
  
  echo
}

function Init()
{ 
  echo "Init..."
  exec 2>&1					# redirect stderr
  
  InitDirs		 >  "$TV_STARTLOG"	|| die "InitDirs failed. ($?)"
  LogStartupInfo >> "$TV_STARTLOG"	|| die "Init failed. Please check '$TV_STARTLOG'"
  UpdateBinaries >> "$TV_STARTLOG"	|| die "UpdateBinaries failed. Please check '$TV_STARTLOG'"

  echo "Checking setup..."
  InitProfile    >> "$TV_STARTLOG"	|| die "InitProfile failed. Please check '$TV_STARTLOG'"  
}

function InitDirs()
{
  cd "$TV_BASE_DIR"			|| return 1		# fonts_portable uses relative path
  make_path "$TV_LOG_DIR"	|| return 2		# needed by LockStartup
}

function LogStartupInfo()
{
  HeadEcho "TeamViewer:"	"$TV_VERSION - $TV_PKGTYPE"
  HeadEcho "Profile:"		"$HOME ($LOGNAME)"
  HeadEcho "Desktop:"		"DS: '$DESKTOP_SESSION' 	XDG: '$XDG_CURRENT_DESKTOP'"
  HeadEcho "XServer TTY:"	"$(InfoXServerTTY)"

  echo
  InfoArch
  InfoDistro

  validateUser	|| return 1			# die if sudo

  echo "ok (info)"
  echo
}

function InfoXServerTTY()
{
  local xfvt
  cmdExists xprop && xfvt=$(xprop -root XFree86_VT | grep INTEGER | cut -f2 -d=)
  xfvt=${xfvt:-'none'}
  echo $xfvt
}

function InfoArch()
{
  local a64=' '; [ -e '/lib64/ld-linux-x86-64.so.2' ] && a64='X'
  local a32=' '; [ -e '/lib/ld-linux.so.2'          ] && a32='X'

  HeadEcho "DistArch:" "$(uname -m)	( Loader:	[$a32] ld32	[$a64] ld64 )"
}

function InfoDistro()				# log information about the Linux distribution
{
  local files=$(cd /etc; ls *-release *-version *_version 2> /dev/null)
  local rfile
  local fhead

  echo     "Distribution:"

  cmdExists lsb_release && fhead=$(lsb_release -idrc)		# first, try lsb_release
  if [ -n "$fhead" ]; then
    IndentEcho "$fhead" '      '
  else
    HeadEcho "  Files" "$(echo "$files" | tr '\n' ' ')"		# try various files
  
    for rfile in $files ; do
      echo "    $rfile:"
      fhead=$(head -n 10 "/etc/$rfile")
      IndentEcho "$fhead" '      '
    done
  fi
}

function Run_TeamViewer()
{
  local tvprofile
  local inst
  local tvdir="$TV_PROFILE/drive_c/TeamViewer"

  isInstalledTV || inst="-n"

  LockStartup || exit 1
  Init

  echo "Launching TeamViewer ..."

  RequireNetwork		# modifies tvprofile !!!
  RequireWineServer

  echo "Launching TeamViewer GUI ..."

  UnlockStartup

  exec wine "c:\TeamViewer\TeamViewer.exe" $inst "${tvprofile[@]}" "$@" &> "$TV_LOG_DIR/winelog"
}

function Run_TeamViewer_Desktop()
{
  [ "$1" = "--desktop" ] && shift

  Init
  echo "Launching TeamViewer_Desktop..."

  RequireWineServer

  exec wine "c:\TeamViewer\TeamViewer_Desktop.exe" "$@" &> "$TV_LOG_DIR/winelogDesktop"
}

function Run_KillTeamViewer()
{
  local this="$0"			# ps: allow user names with more than 8 characters...
  local userlist=$(ps -e -o "user:25,command" | grep -v "^root" | grep TeamViewer | cut --delimiter=' ' -f 1)

  if [ $(id -u) = 0 ] ; then		# if root, launch the script for all other users (except root)
    for user in $userlist ; do
      echo "kill '$this' - $user"
      su -c "$this --kill" - $user
    done
    
    [ -d "$WINEPREFIX" ] && wineserver -k
  else
    wineserver -k	# kill for current user 
  fi
}

function Run_WineCfg()
{
  Init
  wine winecfg "$@"
}

function Run_RegEdit()
{
  Init
  wine regedit "$@"
}

function Run_Daemon()
{
  local opt="$1"
  
  installedTVorDie

  case "$opt" in
    ( disable )					removeDaemon	|| rootSuggest	;;
    ( enable  )					installDaemon	|| rootSuggest	;;
    ( start | stop | restart )	cmdDaemon $opt	|| rootSuggest	;;
    ( status )					cmdDaemon $opt					;;
    ( * )						echo "unknown option '$opt'"	;;
  esac
}
