#!/bin/bash

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

function Init()
{
  local startLog="$TV_LOG_DIR/startup.log"

  echo "Init..."
  make_path        "$TV_LOG_DIR"	|| die "Could not create $TV_LOG_DIR"
  LogStartupInfo > "$startLog"		|| die "Init failed. Please check '$startLog'"
  
  echo "Checking setup..."
  InitProfile   >> "$startLog"		|| die "InitProfile failed. Please check '$startLog'"
}

function LogStartupInfo()
{
  exec 2>&1					# redirect stderr

  echo "TeamViewer: $TV_VERSION"
  echo "Profile: $HOME ($LOGNAME)"
  echo "Desktop: $DESKTOP_SESSION"

  if [ -x "$(type -p lsb_release)" ] ; then	# log information about the Linux distribution
    lsb_release -a
    make_path "$WINEPREFIX/drive_c"
    lsb_release -ds > "$WINEPREFIX/drive_c/distrelease"
  else
    echo /etc/*-release
    for rfile in /etc/*-release ; do		# echo the head of the first valid *-release file
      if [ -e "$rfile" ] ; then
        cat $rfile | head -n 10
        break
      fi
    done
  fi

  validateUser	|| return 1			# die if sudo

  echo "ok"
}


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

function Run_TeamViewer
{
  Init
  echo "Launching TeamViewer..."

  exec 2>&1
  exec > "$TV_LOG_DIR/winelog"
  exec wine "c:\TeamViewer\TeamViewer.exe" "$@"
}

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

  Init
  echo "Launching TeamViewer_Desktop..."

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

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"

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

function SetPasswd()
{
  local pwd="$1"
  [ -n "$pwd" ] || die 'no password specified'

  Run_Daemon 'stop' > /dev/null
  
  $TV_BIN_DIR/teamviewerd --passwd "$pwd"
  case $? in
    0  ) echo 'ok'	;;
    11 ) echo 'password too short - use at least 8 characters'	;;
    12 ) echo 'password too long  - use 12 or less characters'	;;
    13 ) echo 'password not accepted - illegal char detected'	;;
    *  ) echo 'unknown response'	;;
   esac
  
  Run_Daemon 'start' || die 'failed to restart the daemon'
  echo
}

function CreateZipLog()
{
  local cfg_dir="$TV_BASE_DIR/config"
  local log_dir="$TV_BASE_DIR/logfiles"
  local archive="/tmp/tvlog_$(hostname)_$(date +%F)"
  
  echo "Creating a zip archive from all files in $log_dir and $cfg_dir"
  
  cmdExists zip
  if [ $? = 0 ]; then
    rm "$archive.zip"
    archive="$archive.zip"
    zip -r9 $archive $cfg_dir $log_dir || die 'fail'
  else
    rm "$archive.tar.gz"
    archive="$archive.tar.gz"
    tar -zchf $archive $cfg_dir $log_dir || die 'fail'
  fi
  
  echo
  echo "Archive written to $archive"  
  echo 'done'
}

function PrintHelp()
{
  PrintVersion
  echo
  ABecho "teamviewer"		"start TeamViewer user interface (if not running)"
  echo
  ABecho "teamviewer --help"		"print this help screen"
  ABecho "teamviewer --version"		"print version information"
  ABecho "teamviewer --info"		"print version, status, id"
  ABecho "teamviewer --passwd [PASSWD]"	"set a password (useful when installing remote (ssh)"
  ABecho "teamviewer --ziplog"		"create a zip containing all teamviewer logs (useful when contacting support)"
  echo
  ABecho "teamviewer --daemon status"	"show current status of the TeamViewer daemon"
  ABecho "teamviewer --daemon start"	"start		TeamViewer daemon"
  ABecho "teamviewer --daemon stop"	"stop		TeamViewer daemon"
  ABecho "teamviewer --daemon restart"	"stop/start	TeamViewer daemon"
  ABecho "teamviewer --daemon disable"	"disable	TeamViewer daemon - don't start daemon on system startup"
  ABecho "teamviewer --daemon enable"	"enable		TeamViewer daemon - start daemon on system startup (default)"
}

function PrintInfo()
{
  PrintVersion
  echo
  PrintDaemonStatus
  echo
  PrintTeamViewerID
}

function PrintVersion()
{
  ABecho "TeamViewer" "$TV_VERSION"
}

function PrintDaemonStatus()
{
  local cmd="$(daemonCtl 'status')"
  local txt="$(eval "$cmd")"
  [ $? = 0 ] || txt='n/a (error)'
  
  ABecho "teamviewerd status" "$txt"
}

function PrintTeamViewerID
{
  local config="$TV_BASE_DIR/config/global.conf"
  local tvid
  
  [ -e $config ] && tvid=$( grep 'ClientID' $config | cut --delimiter='=' -f2 )

  if [ -n "$tvid" ]; then
    ABecho "TeamViewer ID:" "$tvid"
  else
    echo "TeamViewer ID: not found"
    echo "Try restarting the TeamViewer daemon (e.g. teamviewer --daemon restart)"
  fi
}