#!/bin/bash


# die with message
function die()
{
  echo -e "\nError: $@\n"
  exit 1
}

function ABecho()
{
  printf "\E[1m %-30s \E[0m %s \n" "$1" "$2"
}

function fail()
{
  echo -e "\nError: $@\n"
  false
}

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

function getInitCmd()
{
  #exec 2> /dev/null
  readlink /proc/1/exe 2> /dev/null
  #cat /proc/1/cmdline | tr "\000" " " | cut -d' ' -f1
}

# ensure path exists
function make_path()
{
  local path="$1"
  local mode=${2:+-m $2}
  if [ -d "$path" ] ; then
      # Don't fail here, as chmod is not possible on all file systems
      [ $2 ] && chmod $2 "$path"
      true
  else
      mkdir -p $mode "$path" || fail "Could not create $path"
  fi
}

# real and effective user id should be the same - or the wine-profile could become useless
# TODO: gracefully solve the issue by using su to run wine
function validateUser()
{
  local userid=$(id -un)

  if [ "$userid" != "$USER" ] ; then
    echo -e "\n\n *** TeamViewer can not be executed with sudo! ***\n Either use your normal user account without sudo\n or use a the real root account to log in to your desktop (not recommended!)."
    
    return 1
  fi
}

function isSuperUser # root or sudo
{
  local userid=$(id -u)
  [ "$userid" == 0 ]
}

function rootSuggest()
{
  isSuperUser || echo -e "\nTry with root / sudo ?"
  false
}

function isInstalledTV()
{
  [ "$TV_PKGTYPE" == "DEB"    ] && return 0
  [ "$TV_PKGTYPE" == "RPM"    ] && return 0
  [ "$TV_PKGTYPE" == "TAR"    ] && return 1
  [ "$TV_PKGTYPE" == "TAR_QS" ] && return 1
  
  die 'Invalid package type'
}

function isQuickSupport()
{
  [ "$TV_PKGTYPE" == "TAR_QS" ]
}

function has32BitSupport()
{
  [ -x /lib/ld-linux.so.2 ]
}

function updateMenuEntries()
{
  local action="$1"						# install / uninstall
  xdg-desktop-menu $action --mode system "$TV_DESKTOP_FILE"	# prefer installed xdg script (tvw_config)

  cmdExists update-menus			&& update-menus
  cmdExists update-desktop-database && update-desktop-database
  cmdExists update-icon-caches		&& update-icon-caches /usr/share/icons/hicolor
}
