#!/bin/bash
######################################################################
#                                                                    #
#  Copyright (c) 2002, 2016 NoMachine, http://www.nomachine.com.     #
#                                                                    #
#  All rights reserved.                                              #
#                                                                    #
######################################################################


PACKAGE_NAME="client"
VERSION="5.1.44"
PRODUCT_NAME="NoMachine Client $VERSION"
CONFIG_VERSION="4.0"

RunDir=${0%.uninstall}
RunDir=${RunDir%nxclient}
BinDir=$(cd "$RunDir" && pwd)
NX_ROOT=${BinDir%/scripts/setup}

CONFIG_FILE=""
SELINUX_ENABLED=""


INSTALL="700"
UPDATE="701"
UNINSTALL="702"
WARNING="703"
ERROR="704"
PREFIX="NX>"

LOGFILE=""
NX_VAR_DIR="$NX_ROOT/var"
INSTALLOG="$NX_VAR_DIR/log/nxinstall.log"
UPDATELOG="$NX_VAR_DIR/log/nxupdate.log"
UNINSTALLOG="$NX_VAR_DIR/log/nxuninstall.log"

SHOWUPDATEINFO="no"
SHOWCUPSINFO="no"
SHOWWARNINFO="no"

SETUP_SCRIPT=1



OLD_NX_LOCALIZATION="/usr/NX"
TMP_FOLDER="/tmp"

RUNCOMMAND_NO_ERROR_MESSAGE="run_no_error_message"
RUNCOMMAND_WRONG_PARAMS=1001

USER_NX="nx"
USER_NXHTD="nxhtd"

DISTRO_FILE=""

if [ -x "/bin/pwd" ];
then
  PWDCOMMAND="/bin/pwd"
elif [ -x "/usr/bin/pwd" ];
then
  PWDCOMMAND="/usr/bin/pwd"
else
  PWDCOMMAND="pwd"
fi

if [ -x "/bin/uname" ];
then
  UNAMECOMMAND="/bin/uname"
elif [ -x "/usr/bin/uname" ];
then
  UNAMECOMMAND="/usr/bin/uname"
else
  UNAMECOMMAND="uname"
fi

if [ -x "/bin/head" ];
then
  HEADCOMMAND="/bin/head"
elif [ -x "/usr/bin/head" ];
then
  HEADCOMMAND="/usr/bin/head"
else
  HEADCOMMAND="head"
fi

if [ -x "/bin/tail" ];
then
  TAILCOMMAND="/bin/tail"
elif [ -x "/usr/bin/tail" ];
then
  TAILCOMMAND="/usr/bin/tail"
else
  TAILCOMMAND="tail"
fi

if [ -x "/usr/bin/grep" ]
then
  GREPCOMMAND="/usr/bin/grep"
elif [ -x "/bin/grep" ]
then
  GREPCOMMAND="/bin/grep"
else
  GREPCOMMAND="grep"
fi

getLinuxNameFromFiles ()
{
  #Function returns:
  # 0 : OS name is found
  # 1 : OS name not found

  wantedOS="$1"
  searchedFile=""
  ret_getLinuxNameFromFiles="1"

  if [ -f /etc/lsb-release ];
  then
    searchedFile="/etc/lsb-release"
  elif [ -f /etc/os-release ];
  then
    searchedFile="/etc/os-release"
  elif [ -f /usr/lib/os-release ];
  then
    searchedFile="/usr/lib/os-release"
  else
    return 0
  fi

  os_out=`${GREPCOMMAND} '\(\(NAME\)\|\(DISTRIB_ID\)\)=.*'"${wantedOS}"'.*$' "${searchedFile}" 2>/dev/null || test 1`
  
  if [ "x${os_out}" != "x" ];
  then
      ret_getLinuxNameFromFiles="0"
  fi
}

getLinuxName ()
{
  ret_getLinuxName=0

  getLinuxNameFromFiles "SUSE"

  if [ "x${ret_getLinuxNameFromFiles}" = "x0" ];
  then
    system=suse
    return 0
  fi

  if [ -f /etc/SuSE-release ];
  then
    system=suse

    DISTRO_FILE="/etc/SuSE-release"

    return 0
  fi

  if [ -f /etc/slackware-version ];
  then
      system=slackware

      DISTRO_FILE="/etc/slackware-version"

      return 0
  fi

  if [ -f /etc/mandriva-release ];
  then
    system=mandriva

    DISTRO_FILE="/etc/mandriva-release"

    return 0
  fi

  if [ -f /etc/mandrake-release ];
  then
    system=mandriva

    DISTRO_FILE="/etc/mandrake-release"

    return 0
  fi

  if [ -f /etc/fedora-release ];
  then
    system=fedora

    DISTRO_FILE="/etc/fedora-release"

    return 0
  fi

  if [ -f /etc/redhat-release ];
  then
    system=redhat

    DISTRO_FILE="/etc/redhat-release"

    return 0
  fi

  if [ -f /etc/debian_version ];
  then
    system=debian

    DISTRO_FILE="/etc/debian_version"

    getLinuxNameFromFiles "Ubuntu"

    if [ "x${ret_getLinuxNameFromFiles}" = "x0" ];
    then
      issue=ubuntu
    fi

    getLinuxNameFromFiles "LinuxMint"

    if [ "x${ret_getLinuxNameFromFiles}" = "x0" ];
    then
      issue=linuxmint
    fi

    getLinuxNameFromFiles "elementary"

    if [ "x${ret_getLinuxNameFromFiles}" = "x0" ];
    then
      issue=elementary
    fi

    return 0
  fi

  ret_getLinuxName=1
  return 0
}

getSystemName ()
{
  system=""
  OS=`${UNAMECOMMAND} -s`

  if [ "$OS" = "SunOS" ];
  then
    system="solaris"
  elif [ "$OS" = "Linux" ];
  then
    getLinuxName
    if [ "$ret_getLinuxName" != "0" ];
    then
      system="linux"
    fi
  elif [ "$OS" = "Darwin" ];
  then
    system="macosx"
  fi
}

getSystemName

if [ -x "/bin/rm" ];
then
  RMCOMMAND="/bin/rm"
else
  RMCOMMAND="rm"
fi

if [ -x "/bin/cp" ];
then
  CPCOMMAND="/bin/cp"
else
  CPCOMMAND="cp"
fi

if [ -x "/bin/mv" ];
then
  MVCOMMAND="/bin/mv"
else
  MVCOMMAND="mv"
fi

if [ -x "/bin/ln" ];
then
  LNCOMMAND="/bin/ln"
else
  LNCOMMAND="ln"
fi

if [ -x "/bin/unlink" ];
then
  UNLINKCOMMAND="/bin/unlink"
elif [ -x "/usr/bin/unlink" ];
then
  UNLINKCOMMAND="/usr/bin/unlink"
elif [ -x "/usr/sbin/unlink" ];
then
  UNLINKCOMMAND="/usr/sbin/unlink"
else
  UNLINKCOMMAND="unlink"
fi

if [ -x "/bin/modinfo" ];
then
  MODINFOCOMMAND="/bin/modinfo"
elif [ -x "/usr/bin/modinfo" ];
then
  MODINFOCOMMAND="/usr/bin/modinfo"
elif [ -x "/sbin/modinfo" ];
then
  MODINFOCOMMAND="/sbin/modinfo"
elif [ -x "/usr/sbin/modinfo" ];
then
  MODINFOCOMMAND="/usr/sbin/modinfo"
else
  MODINFOCOMMAND="modinfo"
fi

if [ -x "/bin/ls" ];
then
  LSCOMMAND="/bin/ls"
else
  LSCOMMAND="ls"
fi

if [ -x "/usr/bin/chcon" ];
then
  CHCONCOMMAND="/usr/bin/chcon"
else
  CHCONCOMMAND="chcon"
fi

if [ -x "/usr/bin/restorecon" ];
then
  RESTORECONCOMMAND="/usr/bin/restorecon"
elif [ -x "/sbin/restorecon" ];
then
  RESTORECONCOMMAND="/sbin/restorecon"
else
  RESTORECONCOMMAND="restorecon"
fi

if [ -x "/usr/sbin/getenforce" ];
then
  GETENFORCECOMMAND="/usr/sbin/getenforce"
else
  GETENFORCECOMMAND="getenforce"
fi

if [ -x "/usr/sbin/semanage" ];
then
  SEMANAGECOMMAND="/usr/sbin/semanage"
else
  SEMANAGECOMMAND="semanage"
fi

if [ -x "/usr/sbin/semodule" ];
then
  SEMODULECOMMAND="/usr/sbin/semodule"

else
  SEMODULECOMMAND=""
fi


if [ "$system" = "solaris" ];
then
  if [ -x "/usr/bin/nawk" ];
  then
     AWKCOMMAND="/usr/bin/nawk"
  elif [ -x "/usr/xpg4/bin/awk" ];
  then
    AWKCOMMAND="/usr/xpg4/bin/awk"
  elif [ -x "/usr/bin/awk" ];
  then
    AWKCOMMAND="/usr/bin/awk"
  else
    AWKCOMMAND="awk"
  fi
else
  if [ -x "/usr/bin/awk" ];
  then
    AWKCOMMAND="/usr/bin/awk"
  else
    AWKCOMMAND="awk"
  fi
fi

if [ -x "/usr/sbin/nscd" ];
then
  NSCDCOMMAND="/usr/sbin/nscd"
else
  NSCDCOMMAND="nscd"
fi

if [ -x "/usr/bin/basename" ];
then
  BASENAMECOMMAND="/usr/bin/basename"
else
  BASENAMECOMMAND="basename"
fi

if [ -x "/usr/bin/dirname" ];
then
  DIRNAMECOMMAND="/usr/bin/dirname"
else
  DIRNAMECOMMAND="dirname"
fi

if [ -x "/usr/bin/lsb_release" ];
then
  LSBRELEASECOMMAND="/usr/bin/lsb_release"
else
  LSBRELEASECOMMAND="lsb_release"
fi

if [ -x "/bin/sleep" ];
then
  SLEEPCOMMAND="/bin/sleep"
else
  SLEEPCOMMAND="sleep"
fi

if [ "$system" = "solaris" ];
then
  if [ -x "/usr/xpg4/bin/grep" ]
  then
    GREPCOMMAND="/usr/xpg4/bin/grep"
  elif [ -x "/usr/bin/grep" ]
  then
    GREPCOMMAND="/usr/bin/grep"
  elif [ -x "/bin/grep" ]
  then
    GREPCOMMAND="/bin/grep"
  else
    GREPCOMMAND="grep"
  fi
else
  if [ -x "/usr/bin/grep" ]
  then
    GREPCOMMAND="/usr/bin/grep"
  elif [ -x "/bin/grep" ]
  then
    GREPCOMMAND="/bin/grep"
  else
    GREPCOMMAND="grep"
  fi
fi

if [ -x "/usr/bin/find" ]
then
  FINDCOMMAND="/usr/bin/find"
elif [ -x "/bin/find" ]
then
  FINDCOMMAND="/bin/find"
else
  FINDCOMMAND="find"
fi

if [ "$system" = "solaris" ];
then
  if [ -x "/usr/xpg4/bin/sed" ];
  then
    SEDCOMMAND="/usr/xpg4/bin/sed"
  elif [ -x "/usr/bin/sed" ];
  then
    SEDCOMMAND="/usr/bin/sed"
  elif [ -x "/bin/sed" ];
  then
    SEDCOMMAND="/bin/sed"
  else
    SEDCOMMAND="sed"
  fi
else
  if [ -x "/usr/bin/sed" ];
  then
    SEDCOMMAND="/usr/bin/sed"
  elif [ -x "/bin/sed" ];
  then
    SEDCOMMAND="/bin/sed"
  else
    SEDCOMMAND="sed"
  fi
fi

if [ "$system" = "solaris" ];
then
  if [ -x "/usr/xpg4/bin/id" ]
  then
    IDCOMMAND="/usr/xpg4/bin/id"
  elif [ -x "/usr/bin/id" ]
  then
    IDCOMMAND="/usr/bin/id"
  elif [ -x "/usr/bin/id" ]
  then
    IDCOMMAND="/usr/bin/id"
  else
    IDCOMMAND="id"
  fi
else
  if [ -x "/usr/bin/id" ];
  then
    IDCOMMAND="/usr/bin/id"
  else
    IDCOMMAND="id"
  fi
fi

if [ "$system" = "solaris" ];
then
  if [ -x "/usr/xpg4/bin/make" ]
  then
    MAKECOMMAND="/usr/xpg4/bin/make"
  elif [ -x "/usr/bin/make" ]
  then
    MAKECOMMAND="/usr/bin/make"
  elif [ -x "/bin/make" ]
  then
    MAKECOMMAND="/bin/make"
  else
    MAKECOMMAND="make"
  fi
else
  if [ -x "/bin/make" ];
  then
    MAKECOMMAND="/bin/make"
  else
    MAKECOMMAND="make"
  fi
fi

if [ "$system" = "macosx" ];
then
  if [ -x "/usr/bin/md5" ]
  then
    MD5SUMCOMMAND="/usr/bin/md5"
  elif [ -x "/bin/md5" ]
  then
    MD5SUMCOMMAND="/bin/md5"
  elif [ -x "/sbin/md5" ]
  then
    MD5SUMCOMMAND="/sbin/md5"
  else
    MD5SUMCOMMAND="md5"
  fi
else
  if [ -x "/usr/bin/md5sum" ]
  then
    MD5SUMCOMMAND="/usr/bin/md5sum"
  elif [ -x "/bin/md5sum" ]
  then
    MD5SUMCOMMAND="/bin/md5sum"
  else
    MD5SUMCOMMAND="md5sum"
  fi
fi

if [ -x "/bin/ps" ];
then
  PSCOMMAND="/bin/ps"
elif [ -x "/usr/bin/ps" ];
then
  PSCOMMAND="/usr/bin/ps"
else
  PSCOMMAND="ps"
fi

if [ -x "/bin/sort" ];
then
  SORTCOMMAND="/bin/sort"
elif [ -x "/usr/bin/sort" ];
then
  SORTCOMMAND="/usr/bin/sort"
else
  SORTCOMMAND="sort"
fi

if [ -x "/bin/date" ];
then
  DATECOMMAND="/bin/date"
elif [ -x "/usr/bin/date" ];
then
  DATECOMMAND="/usr/bin/date"
else
  DATECOMMAND="date"
fi

if [ -x "/bin/tail" ];
then
  TAILCOMMAND="/bin/tail"
elif [ -x "/usr/bin/tail" ];
then
  TAILCOMMAND="/usr/bin/tail"
else
  TAILCOMMAND="tail"
fi

if [ -x /bin/mkdir ];
then
  MKDIRCOMMAND="/bin/mkdir"
elif [ -x "/usr/bin/mkdir" ];
then
  MKDIRCOMMAND="/usr/bin/mkdir"
else
  MKDIRCOMMAND="mkdir"
fi

if [ -x "/bin/rmdir" ];
then
  RMDIRCOMMAND="/bin/rmdir"
elif [ -x "/usr/bin/rmdir" ];
then
  RMDIRCOMMAND="/usr/bin/rmdir"
else
  RMDIRCOMMAND="rmdir"
fi

if [ -x "/bin/echo" ];
then
  ECHOCOMMAND="/bin/echo"
elif [ -x "/usr/bin/echo" ];
then
  ECHOCOMMAND="/usr/bin/echo"
else
  ECHOCOMMAND="echo"
fi

if [ -x "/bin/cut" ];
then
  CUTCOMMAND="/bin/cut"
elif [ -x "/usr/bin/cut" ];
then
  CUTCOMMAND="/usr/bin/cut"
else
  CUTCOMMAND="cut"
fi

if [ -x "/bin/cat" ];
then
  CATCOMMAND="/bin/cat"
elif [ -x "/usr/bin/cat" ];
then
  CATCOMMAND="/usr/bin/cat"
else
  CATCOMMAND="cat"
fi

if [ -x "/bin/expr" ];
then
  EXPRCOMMAND="/bin/expr"
elif [ -x "/usr/bin/expr" ];
then
  EXPRCOMMAND="/usr/bin/expr"
else
  EXPRCOMMAND="cat"
fi

if [ -x "/bin/chmod" ];
then
  CHMODCOMMAND="/bin/chmod"
elif [ -x "/usr/bin/chmod" ];
then
  CHMODCOMMAND="/usr/bin/chmod"
else
  CHMODCOMMAND="chmod"
fi

if [ -x /bin/chown ];
then
  CHOWNCOMMAND="/bin/chown"
elif [ -x "/usr/bin/chown" ];
then
  CHOWNCOMMAND="/usr/bin/chown"
elif [ -x /usr/sbin/chown ];
then
  CHOWNCOMMAND="/usr/sbin/chown"
else
  CHOWNCOMMAND="chown"
fi

if [ -x /bin/install ];
then
  INSTALLCOMMAND="/bin/install"
elif [ -x "/usr/bin/install" ];
then
  INSTALLCOMMAND="/usr/bin/install"
elif [ -x /usr/sbin/install ];
then
  INSTALLCOMMAND="/usr/sbin/install"
else
  INSTALLCOMMAND="${NX_ROOT}/scripts/setup/install"
fi

if [ -x "/bin/touch" ];
then
  TOUCHCOMMAND="/bin/touch"
elif [ -x "/usr/bin/touch" ];
then
  TOUCHCOMMAND="/usr/bin/touch"
else
  TOUCHCOMMAND="touch"
fi

if [ -x "/bin/tr" ];
then
  TRCOMMAND="/bin/tr"
elif [ -x "/usr/bin/tr" ];
then
  TRCOMMAND="/usr/bin/tr"
else
  TRCOMMAND="tr"
fi

if [ -x "/bin/kill" ];
then
  KILLCOMMAND="/bin/kill"
elif [ -x "/usr/bin/kill" ];
then
  KILLCOMMAND="/usr/bin/kill"
else
  KILLCOMMAND="kill"
fi

if [ -x "/bin/killall" ];
then
  KILLALLCOMMAND="/bin/killall"
elif [ -x "/usr/bin/killall" ];
then
  KILLALLCOMMAND="/usr/bin/killall"
elif [ -x "/usr/sbin/killall" ];
then
  KILLALLCOMMAND="/usr/sbin/killall"
else
  KILLALLCOMMAND="killall"
fi

if [ -x "/sbin/pidof" ];
then
  PIDOFCOMMAND="/sbin/pidof"
else
  PIDOFCOMMAND="pidof"
fi

if [ -x "/bin/tee" ];
then
  TEECOMMAND="/bin/tee"
elif [ -x "/usr/bin/tee" ];
then
  TEECOMMAND="/usr/bin/tee"
else
  TEECOMMAND="tee"
fi

if [ -x "/bin/readlink" ];
then
  READLINKCOMMAND="/bin/readlink"
elif [ -x "/usr/bin/readlink" ];
then
  READLINKCOMMAND="/usr/bin/readlink"
else
  READLINKCOMMAND="readlink"
fi

if [ -x "/bin/gunzip" ];
then
  GUNZIPCOMMAND="/bin/gunzip"
elif [ -x "/usr/bin/gunzip" ];
then
  GUNZIPCOMMAND="/usr/bin/gunzip"
else
  GUNZIPCOMMAND="gunzip"
fi

if [ -x "/bin/tar" ];
then
  TARCOMMAND="/bin/tar"
elif [ -x "/usr/bin/tar" ];
then
  TARCOMMAND="/usr/bin/tar"
else
  TARCOMMAND="tar"
fi

if [ -x "/usr/bin/du" ];
then
  DUCOMMAND="/usr/bin/du"
else
  DUCOMMAND="du"
fi

if [ -x "/usr/bin/ypcat" ];
then
  YPCATCOMMAND="/usr/bin/ypcat"
else
  YPCATCOMMAND="ypcat"
fi

if [ -x "/usr/bin/printf" ];
then
  PRINTFCOMMAND="/usr/bin/printf"
else
  PRINTFCOMMAND="printf"
fi

if [ -x "/usr/bin/which" ];
then
  WHICHCOMMAND="/usr/bin/which"
else
  WHICHCOMMAND="which"
fi

if [ -x "/usr/sbin/sw_vers" ];
then
  SWVERSCOMMAND="/usr/sbin/sw_vers"
elif [ -x "/usr/bin/sw_vers" ];
then
  SWVERSCOMMAND="/usr/bin/sw_vers"
elif [ -x "/bin/sw_vers" ];
then
  SWVERSCOMMAND="/bin/sw_vers"
elif [ -x "/sbin/sw_vers" ];
then
  SWVERSCOMMAND="/sbin/sw_vers"
else
  SWVERSCOMMAND="sw_vers"
fi

if [ -x "/usr/bin/dscl" ];
then
  DSCLCOMMAND="/usr/bin/dscl"
else
  DSCLCOMMAND="dscl"
fi

if [ -x "/usr/sbin/createhomedir" ];
then
  CREATEHOMEDIRCOMMAND="/usr/sbin/createhomedir"
else
  CREATEHOMEDIRCOMMAND="createhomedir"
fi

if [ -x "/bin/systemctl" ];
then
  SYSTEMCTLCOMMAND="/bin/systemctl"
else
  SYSTEMCTLCOMMAND="systemctl"
fi

if [ -x "/sbin/ldconfig" ];
then
  LDCONFIGCOMMAND="/sbin/ldconfig"
else
  LDCONFIGCOMMAND="ldconfig"
fi

if [ -x "/usr/bin/objdump" ];
then
  OBJDUMPCOMMAND="/usr/bin/objdump"
else
  OBJDUMPCOMMAND="objdump"
fi

if [ -x "/usr/sbin/adduser" ];
then
  ADDUSERCOMMAND="/usr/sbin/adduser"
else
  ADDUSERCOMMAND="adduser"
fi

if [ -x "/usr/sbin/useradd" ];
then
  USERADDCOMMAND="/usr/sbin/useradd"
else
  USERADDCOMMAND="useradd"
fi

if [ -x "/usr/sbin/userdel" ];
then
  USERDELCOMMAND="/usr/sbin/userdel"
else
  USERDELCOMMAND="userdel"
fi

if [ -x "/usr/sbin/usermod" ];
then
  USERMODCOMMAND="/usr/sbin/usermod"
else
  USERMODCOMMAND="usermod"
fi

if [ -x "/usr/sbin/groupadd" ];
then
  GROUPADDCOMMAND="/usr/sbin/groupadd"
else
  GROUPADDCOMMAND="groupadd"
fi

if [ -x "/usr/sbin/groupdel" ];
then
  GROUPDELCOMMAND="/usr/sbin/groupdel"
else
  GROUPDELCOMMAND="groupdel"
fi

if [ -x "/bin/su" ];
then
  SUCOMMAND="/bin/su"
elif [ -x "/usr/bin/su" ];
then
  SUCOMMAND="/usr/bin/su"
else
  SUCOMMAND="su"
fi

if [ -x "/bin/sudo" ];
then
  SUDOCOMMAND="/bin/sudo"
elif [ -x "/usr/bin/sudo" ];
then
  SUDOCOMMAND="/usr/bin/sudo"
else
  SUDOCOMMAND="sudo"
fi

if [ -x "/bin/launchctl" ];
then
  LAUNCHCTLCOMMAND="/bin/launchctl"
elif [ -x "/usr/bin/launchctl" ];
then
  LAUNCHCTLCOMMAND="/usr/bin/launchctl"
else
  LAUNCHCTLCOMMAND="launchctl"
fi

if [ -x "/bin/sysctl" ];
then
  SYSCTLCOMMAND="/bin/sysctl"
elif [ -x "/usr/bin/sysctl" ];
then
  SYSCTLCOMMAND="/usr/bin/sysctl"
elif [ -x "/usr/sbin/sysctl" ];
then
  SYSCTLCOMMAND="/usr/sbin/sysctl"
else
  SYSCTLCOMMAND="sysctl"
fi

if [ -x "/bin/wc" ];
then
  WCCOMMAND="/bin/wc"
elif [ -x "/usr/bin/wc" ];
then
  WCCOMMAND="/usr/bin/wc"
elif [ -x "/usr/sbin/wc" ];
then
  WCCOMMAND="/usr/sbin/wc"
else
  WCCOMMAND="wc"
fi

if [ -x "/usr/bin/ssh-keygen" ]; then
  KEYGENCOMMAND="/usr/bin/ssh-keygen"
elif [ -x "/bin/ssh-keygen" ]; then
  KEYGENCOMMAND="/bin/ssh-keygen"
else
  KEYGENCOMMAND="ssh-keygen"
fi

if [ -x "/usr/bin/execstack" ];
then
  EXECSTACKCOMMAND="/usr/bin/execstack"
else
  EXECSTACKCOMMAND="execstack"
fi

if [ -x "/usr/bin/update-mime-database" ];
then
  UPDATEMIMEDATABASECOMMAND="/usr/bin/update-mime-database"
else
  UPDATEMIMEDATABASECOMMAND="update-mime-database"
fi

if [ -x "/usr/bin/update-desktop-database" ];
then
  UPDATEDESKTOPDATABASECOMMAND="/usr/bin/update-desktop-database"
else
  UPDATEDESKTOPDATABASECOMMAND="update-desktop-database"
fi

if [ -x "/usr/bin/xdg-open" ];
then
  XDGOPENCOMMAND="/usr/bin/xdg-open"
else
  XDGOPENCOMMAND="xdg-open"
fi

if [ -x "/usr/bin/xdg-mime" ];
then
  XDGMIMECOMMAND="/usr/bin/xdg-mime"
else
  XDGMIMECOMMAND="xdg-mime"
fi

if [ -x "/usr/bin/xdg-icon-resource" ];
then
  XDGICONRESOURCECOMMAND="/usr/bin/xdg-icon-resource"
else
  XDGICONRESOURCECOMMAND="xdg-icon-resource"
fi

if [ -x "/usr/bin/xdg-desktop-menu" ];
then
  XDGDESKTOPMENUCOMMAND="/usr/bin/xdg-desktop-menu"
else
  XDGDESKTOPMENUCOMMAND="xdg-desktop-menu"
fi

if [ -x "/usr/bin/gtk-update-icon-cache" ];
then
  GTKUPDATEICONCACHECOMMAND="/usr/bin/gtk-update-icon-cache"
elif [ -x "/bin/gtk-update-icon-cache" ];
then
  GTKUPDATEICONCACHECOMMAND="/bin/gtk-update-icon-cache"
elif [ -x "/usr/sbin/gtk-update-icon-cache" ];
then
  GTKUPDATEICONCACHECOMMAND="/usr/sbin/gtk-update-icon-cache"
else
  GTKUPDATEICONCACHECOMMAND=""
fi

if [ -x "/usr/bin/X11/gnome-terminal" ];
then
  GNOMETERMINALCOMMAND="/usr/bin/X11/gnome-terminal"
elif [ -x "/usr/bin/gnome-terminal" ];
then
  GNOMETERMINALCOMMAND="/usr/bin/gnome-terminal"
elif [ -x "/bin/gnome-terminal" ];
then
  GNOMETERMINALCOMMAND="/bin/gnome-terminal"
else
  GNOMETERMINALCOMMAND="gnome-terminal"
fi

if [ -x "/usr/bin/X11/xterm" ];
then
  XTERMCOMMAND="/usr/bin/X11/xterm"
elif [ -x "/usr/bin/xterm" ];
then 
  XTERMCOMMAND="/usr/bin/xterm"
elif [ -x "/bin/xterm" ];
then
  XTERMCOMMAND="/bin/xterm"
else
  XTERMCOMMAND="xterm"
fi

if [ -x "/usr/bin/X11/konsole" ];
then
  KONSOLECOMMAND="/usr/bin/X11/konsole"
elif [ -x "/usr/bin/konsole" ];
then
  KONSOLECOMMAND="/usr/bin/konsole"
elif [ -x "/bin/konsole" ];
then
  KONSOLECOMMAND="/bin/konsole"
else
  KONSOLECOMMAND="konsole"
fi

if [ -x "/usr/bin/X11/xfce4-terminal" ];
then
  XFCE4COMMAND="/usr/bin/X11/xfce4-terminal"
elif [ -x "/usr/bin/xfce4-terminal" ];
then
  XFCE4COMMAND="/usr/bin/xfce4-terminal"
elif [ -x "/bin/xfce4-terminal" ];
then
  XFCE4COMMAND="/bin/xfce4-terminal"
else
  XFCE4COMMAND="xfce4-terminal"
fi

if [ -x "/usr/bin/runcon" ];
then
  RUNCONCOMMAND="/usr/bin/runcon"
else
  RUNCONCOMMAND="runcon"
fi

if [ -x "/usr/bin/chkconfig" ];
then
  CHKCONFIGCOMMAND="/usr/bin/chkconfig"
else
  CHKCONFIGCOMMAND="chkconfig"
fi

if [ -x "/sbin/insserv" ];
then
  INSSERVCOMMAND="/sbin/insserv"
elif [ -x "/usr/bin/insserv" ];
then
  INSSERVCOMMAND="/usr/bin/insserv"
else
  INSSERVCOMMAND="insserv"
fi

if [ -x "/usr/sbin/update-rc.d" ];
then
  UPDATERCDCOMMAND="/usr/sbin/update-rc.d"
else
  UPDATERCDCOMMAND="update-rc.d"
fi

if [ -x "/usr/bin/arch" ];
then
  ARCHCOMMAND="/usr/bin/arch"
else
  ARCHCOMMAND="arch"
fi

if [ -x "/usr/bin/strip" ];
then
  STRIPCOMMAND="/usr/bin/strip"
else
  STRIPCOMMAND="strip"
fi

if [ -x "/usr/bin/ssh-keyscan" ];
then
  KEYSCANCOMMAND="/usr/bin/ssh-keyscan"
elif [ -x "/bin/ssh-keyscan" ];
then
  KEYSCANCOMMAND="/bin/ssh-keyscan"
else
  KEYSCANCOMMAND="ssh-keyscan"
fi

BASHSHELL="/bin/bash"

NXSHELL="/etc/NX/nxserver"
if [ "$system" = "macosx" ];
then
  ROOTGNAME=`$IDCOMMAND -gn root`
  NXUSERHOME="/Library/Application Support/NoMachine/var"
else
  ROOTGNAME="root"
  NXUSERHOME="/var/NX"
fi

NXHOME="${NXUSERHOME}/${USER_NX}"

SERVER_USR_CONFIG_FILE="${NX_ROOT}/etc/server.cfg"
NODE_USR_CONFIG_FILE="${NX_ROOT}/etc/node.cfg"
WEBPLAYER_USR_CONFIG_FILE="${NX_ROOT}/etc/cloud.cfg"

currentTime=`${DATECOMMAND} +'%a %b %d %T %Y'`

LAST_SUBPACKAGE_SERVER="server"
LAST_SUBPACKAGE_NODE="node"
LAST_SUBPACKAGE_PLAYER="player"
LAST_SUBPACKAGE_WEBPLAYER="webplayer"

isDevel ()
{
  if [ "x${NX_INSTALL_DEVEL}" = "x" ];
  then
    NX_INSTALL_DEVEL=0
    if [ -f "/${TMP_FOLDER}/nxtimedevel" ];
    then
      NX_INSTALL_DEVEL=1
    fi
  fi
}

# printMsg() procedure take argument : txt
# echo(echo and log) log (only log) nolog (only echo)
# default - using PROCESS - WARNINGS/ERRORS
#

isDevel

printMsgNoDot ()
{
  severity=$2

  if [ "${SETUP_SCRIPT}" = "1" ];
  then
    TXT=$1

    if [ "${TXT}" = "" ];
    then
      return 0
    fi

    if [ "x${NX_INSTALL_DEVEL}" = "x1" ];
    then
      if [ "x${system}" = "xmacosx" ] && [ -x "/${TMP_FOLDER}/nxdate" ];
      then
        TIME_DEVEL=`/${TMP_FOLDER}/nxdate 2>/dev/null`
      else
        TIME_DEVEL=`${DATECOMMAND} "+%H:%M:%S:%N" 2>/dev/null`
      fi

      TIME_DEVEL="${TIME_DEVEL} "
    fi

    if [ "${PROCESS}" = "" ];
    then
      PROCESS="${ERROR}"
    fi

    case "$severity" in
      "warn"      ) process="${WARNING}";TXT="WARNING: ${TXT}";logtype="log";SHOWWARNINFO="yes";;
      "warnshow"  ) process="${WARNING}";TXT="WARNING: ${TXT}";logtype="show";SHOWWARNINFO="yes";;
      "error"     ) process="${ERROR}";TXT="ERROR: ${TXT}";logtype="show";SHOWWARNINFO="yes";;
      "cmd"       ) process="${PROCESS}";logtype="log";;
      "nolog"     ) process="${PROCESS}";logtype="nolog";;
      "onlylog"   ) process="${PROCESS}";logtype="onlylog";;
      "nonewline" ) process="${PROCESS}";logtype="nonewline";;
      ""          ) process="${PROCESS}";logtype="show";;
      *           ) process="${PROCESS}";;
    esac

    if [ "${LOGFILE}" = "" ];
    then
      if [ "${logtype}" = "onlylog" ];
      then
        return
      fi

      logtype="nolog"
    elif [ "${logtype}" = "onlylog" ];
    then
      logtype="log"
    fi

    if [ "$3" = "1" ];
    then
      TXT="$TXT."
    fi

    case "$logtype" in
      "nolog"      ) ${ECHOCOMMAND} "${TIME_DEVEL}$PREFIX ${PROCESS} ${TXT}";;
      "log"        ) ${ECHOCOMMAND} "${TIME_DEVEL}$PREFIX ${PROCESS} ${TXT}" >> "${LOGFILE}";;
      "show"       ) ${ECHOCOMMAND} "${TIME_DEVEL}$PREFIX ${PROCESS} ${TXT}";${ECHOCOMMAND} "${PREFIX} ${PROCESS} ${TXT}" >> "${LOGFILE}";;
      "nonewline"  ) ${ECHOCOMMAND} -n "${TIME_DEVEL}$PREFIX ${PROCESS} ${TXT}";${ECHOCOMMAND} "${PREFIX} ${PROCESS} ${TXT}" >> "${LOGFILE}";;
      ""           ) ${ECHOCOMMAND} "${TIME_DEVEL}$PREFIX ${PROCESS} ${TXT}";;
      *            ) ${ECHOCOMMAND} "${TIME_DEVEL}$PREFIX ${PROCESS} ${TXT}";;
    esac

    case "$severity" in
      "warn"     ) setInstallationWarning;;
      "warnshow" ) setInstallationWarning;;
      "error"    ) setInstallationError;;
    esac

  else
    if [ "x$1" != "x" ];
    then
      if [ "x$2" = "x0" ];
      then
        ${ECHOCOMMAND} "${1}"
      fi
    fi
  fi
}

printMsg ()
{
  WITH_DOT=1
  printMsgNoDot "$1" "$2" "${WITH_DOT}"
}

runShCommand ()
{
  ret_runShCommand=0

  if [ "$1" = "" ];
  then
    ret_runShCommand=1
    return 0
  else
    command="$1"
  fi

  outCommand=`${BASHSHELL} -c "${command}" 2>&1`

  if [ $? != 0 ];
  then
    if [ "${SCRIPT_SETUP}" = "1" ];
    then
      LastCommand="Error is: ${outCommand}"
    else
      printMsg "ERROR: ${outCommand}" $2
    fi
  fi
}

getDefalutMsgForCommand ()
{
  ret_getDefalutMsgForCommand=0

  if [ "x$1" = "x" ];
  then
    defMsg="Error while executing this command"
    ret_getDefalutMsgForCommand=1
    return 0
  else
    outcmd=`${ECHOCOMMAND} "$1" | ${CUTCOMMAND} -f1 -d " "`
    if [ "x${outcmd}" = "x" ];
    then
      defMsg="Error while executing '$1'"
      ret_getDefalutMsgForCommand=1
      return 0
    else
      case "${outcmd}" in
        "mkdir")  "Cannot create directory"
      esac
    fi
  fi
}

runCommand ()
{
  ret_runCommand=0

  if [ "$1" = "" ];
  then
    ret_runCommand=${RUNCOMMAND_WRONG_PARAMS}
    return 0
  else
    command="$1"
  fi

  if [ "$2" = "" ];
  then
    ret_runCommand=${RUNCOMMAND_WRONG_PARAMS}
    return 0
  else
    message="$2"
  fi

  if [ "$3" = "" ];
  then
    important="NO"
  else
    important="YES"
  fi

  if [ "${SETUP_SCRIPT}" = "1" ] && [ "x$3" != "xnolog" ];
  then
    printMsg "Running: ${command}" "cmd"
  fi

  outCommand=`${BASHSHELL} -c "${command}" 2>&1`
  rc_return=$?
  if [ ${rc_return} != 0 ];
  then
    if [ "${SCRIPT_SETUP}" = "1" ];
    then

      if [ "${important}" = "YES" ];
      then
        if [ "x${outCommand}" != "x" ] && [ "x$3" != "xnolog" ];
        then
          printMsg "Result: ${outCommand}" "error"
        fi

        if [ "${message}" !=  "${RUNCOMMAND_NO_ERROR_MESSAGE}" ];
        then
          printMsg "${message}" "error"
        fi

        exit 1
      else
        if [ "x${outCommand}" != "x" ];
        then
          printMsg "Result: ${outCommand}" "cmd"
        fi

        if [ "${message}" !=  "${RUNCOMMAND_NO_ERROR_MESSAGE}" ];
        then
          printMsg "${message}" "warn"
        fi
      fi
    else
      if [ "${message}" !=  "${RUNCOMMAND_NO_ERROR_MESSAGE}" ];
      then
        printMsg "${message}" "$3"
      fi
    fi
  else
    if [ "x${outCommand}" != "x" ];
    then
      if [ "x$3" = "xnolog" ];
      then
        printMsg "Running: ${command}" "cmd"
      fi

      printMsg "Result: ${outCommand}" "cmd"
    fi

    if [ "x$3" != "xnolog" ];
    then
      printMsg "Result: OK" "cmd"
    fi
  fi

  ret_runCommand=${rc_return}
  return 0
}

printMsgDebug ()
{
  #NX_INSTALL_DEBUG=1
  if [ "x$1" != "x" ] && [ "${NX_INSTALL_DEBUG}" = "1" ];
  then
    if [ "x${LOGFILE}" = "x" ];
    then
      ${ECHOCOMMAND} "DEBUG: $1"
    else
      ${ECHOCOMMAND} "DEBUG: $1" >> "${LOGFILE}"
    fi
  fi
}

printMsgDebugReturn ()
{
  #Params:
  #1 - function name
  #2 - returned value

  printMsgDebug "$1: return $2"
}

CFG_CLIENT_ROOT="ClientRoot"
CFG_PLAYER_ROOT="PlayerRoot"
CFG_NODE_ROOT="NodeRoot"
CFG_SERVER_ROOT="ServerRoot"
CFG_CONNECT_ROOT="ConnectRoot"
CFG_WEBPLAYER_ROOT="WebPlayerRoot"
CFG_USBREDIRECTOR_ROOT="UsbRedirectorRoot"

setPackageVariables()
{
  ETC_CONFIG_FILE=""

  if [ "x${NX_MPKG_PACKAGE}" != "x" ];
  then
    #NX_MPKG_PACKAGE=${PACKAGE_NAME}
    ETC_CONFIG_FILE="/etc/NX/${NX_MPKG_PACKAGE}/localhost/${PACKAGE_NAME}.cfg"
  fi
}

setPackageVariables

isRoot ()
{
  ret_isRoot=0
  id_out=`${IDCOMMAND} -u`
  if [ "x${id_out}" = "x0" ];
  then
    ret_isRoot=1
    return 0
  fi

  return 0
}

checkNXUserExist ()
{
  ret_checkNXUserExist=0
  id_out=`${IDCOMMAND} -u ${USER_NX} > /dev/null 2>&1`
  if [ "$?" = "0" ];
  then
    ret_checkNXUserExist=1
    return 0
  fi

  return 0
}

checkUserExist ()
{
  user=$1
  ret_checkUserExist=0

  if [ "x$user" = "x" ];
  then
    ret_checkUserExist=1
    return 0
  fi

  id_out=`${IDCOMMAND} -u ${user} > /dev/null 2>&1`
  if [ "$?" = "0" ];
  then
    ret_checkUserExist=1
    return 0
  fi

  return 0
}

checkUserExistPasswd ()
{
  user=$1
  ret_checkUserExistPasswd=0

  user_out=`${GREPCOMMAND} "^${user}:" /etc/passwd 2>/dev/null | ${AWKCOMMAND} -F ":" '{print $1}'`
  if [ "x${user_out}" = "x${user}" ];
  then
    ret_checkUserExistPasswd=1
    return 0
  fi

  return 0
}

getRootCfgName()
{
  printMsgDebug "getRootCfgName: ($1)"

  package=$1
  ret_getRootCfgName=0
  ret_CFGRootName=""

  if [ "x${package}" = "xclient" ];
  then
    ret_CFGRootName=$CFG_CLIENT_ROOT
  elif [ "x${package}" = "xplayer" ];
  then
    ret_CFGRootName=$CFG_PLAYER_ROOT
  elif [ "x${package}" = "xnode" ];
  then
    ret_CFGRootName=$CFG_NODE_ROOT
  elif [ "x${package}" = "xserver" ];
  then
    ret_CFGRootName=$CFG_SERVER_ROOT
  elif [ "x${package}" = "xwebplayer" ];
  then
    ret_CFGRootName=$CFG_WEBPLAYER_ROOT
  elif [ "x${package}" = "xconnect" ];
  then
    ret_CFGRootName=$CFG_CONNECT_ROOT
  elif [ "x${package}" = "xusb" ];
  then
    ret_CFGRootName=$CFG_USBREDIRECTOR_ROOT
  elif [ "x${package}" = "xavc" ];
  then
    ret_CFGRootName=$CFG_CLIENT_ROOT
  else
    ${ECHOCOMMAND} "ERROR: Unknown package -- ${package}"
    ret_getRootCfgName=1
  fi
}

getConfigFileName ()
{
#Par1 - package name, i.e. client, node, server
#Par2 - product name, i.e. player, node, server, connect

  printMsgDebug "getConfigFileName: ($1,$2)"

  if [ "x$2" != "x" ];
  then
    product_name=$2
  elif [ "x${NX_MPKG_PACKAGE}" != "x" ];
  then
    product_name=${NX_MPKG_PACKAGE}
  else
    product_name=$1
  fi

  if [ "x$1" = "xconnect" ];
  then
    isRoot
    if [ ${ret_isRoot} = 1 ];
    then
      ret_getConfigFileName="/etc/NX/${product_name}/localhost/${1}.cfg"
    else
      ret_getConfigFileName="${HOME}/.nx/config/server/${product_name}/localhost/server.cfg"
    fi
  elif [ "x$1" = "xwebclient" ];
  then
    ret_getConfigFileName="/etc/NX/${product_name}/localhost/webplayer.cfg"
  else
    ret_getConfigFileName="/etc/NX/${product_name}/localhost/${1}.cfg"
  fi
}

trimLeft ()
{
  ret="${1%"${1##*[![:space:]]}"}"
}

trimRight ()
{
  ret="${1#"${1%%[![:space:]]*}"}"
}

trimBoth ()
{
  trimLeft "$1"
  trimRight "${ret}"
}

trimLeftQuota ()
{
  ret="${1%\"}"
}

trimRightQuota ()
{
  ret="${1#\"}"
}

trimBothQuota ()
{
  trimLeftQuota "$1"
  trimRightQuota "${ret}"
}


getValueFromCfgFile ()
{
  #Config File Format:  Variable = Value or Variable = "Value"

  #Parameters:
  # $1 - Variable
  # $2 - File name
  #Function returns:
  # 0 : no such variable or no such file
  # 1 : variable is commented (default value)
  # 2 : variable exists, value returned in cfg_val

  printMsgDebug "getValueFromCfgFile: ($1,$2)"
  ret_getValueFromCfgFile=0

  variable=$1
  file_name=$2
  cfg_val=""

  if [ ! -f "${file_name}" ] || [ "x${variable}" = "x" ];
  then
    return 0
  fi

  grep_out=`${GREPCOMMAND} -E "^([[:space:]]){0,}${variable}([[:space:]]){1,}" "${file_name}" 2>/dev/null`
  if [ "x${grep_out}" = "x" ];
    then
    grep_out=`${GREPCOMMAND} -E "^([[:space:]]){0,}[#]{0,1}([[:space:]]){0,}${variable}([[:space:]]){1,}" "${file_name}" 2>/dev/null`
  fi

  if [ "x${grep_out}" != "x" ];
  then
    grep_commented=`${GREPCOMMAND} -e "${grep_out}" "${file_name}" | ${HEADCOMMAND} -n 1 | ${AWKCOMMAND} '{ if (index($1,"#")==1) print "0"; else print "1" }' 2>/dev/null`
    if [ ${grep_commented} = 0 ];
    then
      cfg_val=`${ECHOCOMMAND} ${grep_out} | ${AWKCOMMAND} -F '\"' '{print $2}'`
      if [ "x${cfg_val}" = "x" ];
      then
        cfg_val=`${ECHOCOMMAND} ${grep_out} | ${AWKCOMMAND} -v FS="${variable}"'[ \t]+' '{print $NF}'`
      fi
      ret_getValueFromCfgFile=1
      return 0
    else
      cfg_val=`${ECHOCOMMAND} ${grep_out} | ${AWKCOMMAND} -F '\"' '{print $2}'`
      if [ "x${cfg_val}" = "x" ];
      then
        cfg_val=`${ECHOCOMMAND} ${grep_out} | ${AWKCOMMAND} -v FS="${variable}"'[ \t]+' '{print $NF}'`
      fi
      ret_getValueFromCfgFile=2
      return 0
    fi
  else
    return 0
  fi
}

setValueAtCfgFile ()
{
  #Config File Format:  Variable = Value or Variable = "Value".

  #Parameters:
  # $1 - File name
  # $2 - Variable
  # $3 - New value
  #Function returns:
  # 0 : no such variable or no such file
  # 1 : variable was commented
  # 2 : variable exists

  printMsgDebug "${FUNCNAME}: ($1,$2,$3)"
  ret_setValueAtCfgFile=0

  file_name="$1"
  variable="$2"
  new_value="$3"

  pos=`${EXPRCOMMAND} "${new_value}" : '.*\(.*[[:space:]].*\)'`
  grep_out=`${GREPCOMMAND} -E "^([[:space:]]){0,}${variable}([[:space:]]){1,}" "${file_name}" 2>/dev/null`

  if [ "x${grep_out}" != "x" ];
  then
    if [ "x${pos}" = "x" ];
    then
      ${SEDCOMMAND} -e 's|^[[:space:]]*'"${variable}"'[[:space:]]*.*|'"${variable}"' '"${new_value}"'|' "${file_name}" > "${file_name}.tmp"
    else
      ${SEDCOMMAND} -e 's|^[[:space:]]*'"${variable}"'[[:space:]]*.*|'"${variable}"' \"'"${new_value}"'\"|' "${file_name}" > "${file_name}.tmp"
    fi
    commandRestoreFile "${file_name}" "tmp"
    ret_setValueAtCfgFile=2
    return 0
  fi

  grep_out=`${GREPCOMMAND} -E "^([[:space:]]){0,}[#]{0,1}([[:space:]]){0,}${variable}([[:space:]]){1,}" "${file_name}" 2>/dev/null`
  if [ "x${grep_out}" != "x" ];
  then
    if [ "x${pos}" = "x" ];
    then
      ${SEDCOMMAND} -e 's|^[[:space:]]*[#]*[[:space:]]*'"${variable}"'[[:space:]]*.*|'"${variable}"' '"${new_value}"'|' "${file_name}" > "${file_name}.tmp"
    else
      ${SEDCOMMAND} -e 's|^[[:space:]]*[#]*[[:space:]]*'"${variable}"'[[:space:]]*.*|'"${variable}"' \"'"${new_value}"'\"|' "${file_name}" > "${file_name}.tmp"
    fi

    commandRestoreFile "${file_name}" "tmp"
    ret_setValueAtCfgFile=1
    return 0
  fi

  return 0
}

changeKeyAtConfigFile ()
{
  file_name="$1"
  key="$2"
  new_value="$3"

  ret_changeKeyAtConfigFile=0
  setValueAtCfgFile "${file_name}" "${key}" "${new_value}"
  if [ ${ret_setValueAtCfgFile} != 0 ];
  then
    printMsgUpdatedKeyinConfigFile "${key}" "${new_value}"
    return 0
  else
    printMsg "ERROR: Cannot add key: ${key}" "cmd"
    ret_changeKeyAtConfigFile=1
    return 0
  fi
}

getPackagePath()
{
#Par1 - package name, i.e. client, node, server

  printMsgDebug "getPackagePath: ($1)"

  ret_getPackagePath=0
  ret_packagePath=""

  package_name="$1"
  if [ "x${package_name}" = "x" ];
  then
    ret_getPackagePath=1
    return 0
  fi

  if [ "x${system}" = "xmacosx" ];
  then
    if [ "${package_name}" = "server" ];
    then
      #ret_packagePath="/Applications/NoMachine Service.app/Contents/Frameworks"
      ret_packagePath="/Applications/NoMachine.app/Contents/Frameworks"
      return 0
    elif [ "${package_name}" = "node" ];
    then
      ret_packagePath="/Applications/NoMachine Node.app/Contents/Frameworks"
      return 0
    elif [ "${package_name}" = "player" ];
    then
      ret_packagePath="/Applications/NoMachine.app/Contents/Frameworks"
      ROOTDIR="${ret_packagePath}"
      return 0
    fi

    ret_getPackagePath=1
    return 0
  fi

  getRootCfgName ${package_name}
  if [ "${ret_getRootCfgName}" != "0" ] || [ "x${ret_CFGRootName}" = "x" ];
  then
    ret_getPackagePath=1
    return 0
  fi

  getConfigFileName "${package_name}" "${package_name}"

  if [ ! -f "${ret_getConfigFileName}" ];
  then
    getConfigFileName "server" "node"
    getValueFromCfgFile "${ret_CFGRootName}" "${ret_getConfigFileName}"
  else
    getValueFromCfgFile "${ret_CFGRootName}" "${ret_getConfigFileName}"
  fi

  if [ "${ret_getValueFromCfgFile}" = "2" ];
  then
    #FIXME: ROOTDIR variable has to be removed
    ROOTDIR="${cfg_val}"
    ret_packagePath="${cfg_val}"
    return 0
  else
    ret_getPackagePath=1
    return 0
  fi
}

getCfgFileVersion ()
{
  package_name=$1
  installation_path="$2"
  suffix_path="$3"

  cfg_version=""

  printMsgDebug "getCfgFileVersion: ($1,$2)"
  ret_getCfgFileVersion=0

  if [ "x${suffix_path}" = "x" ];
  then
    config_file="${installation_path}/etc/${package_name}.cfg"
  else
    config_file="${installation_path}/etc/${package_name}.cfg${suffix_path}"
  fi

  printMsgDebug "Config file: '${config_file}'"

  if [ -f "${config_file}" ];
  then
    cfg_version=`${GREPCOMMAND} -i "^configfileversion" "${config_file}" | ${AWKCOMMAND} '{if ($2 == "=" ) print $3; else print $2}' | ${SEDCOMMAND} -e 's/\"//g'`
    printMsgDebug "Config file version: ${cfg_version}."

  else
    printMsgDebug  "WARNING: Cannot find file: ${config_file}."
    ret_getCfgFileVersion=1
    return 0
  fi
}

__removeETCDirectory ()
{
  package_name="$1"

  if [ ! -d "${ETC_DIR}" ];
  then
    return 0
  fi

  commandRmIfExist "${ETC_DIR}/nx${package_name}" "cmd"
  commandRmIfExist "${ETC_CONFIG_FILE}" "cmd"
  commandRmIfExist "${ETC_CONFIG_FILE}.sample" "cmd"

  commandRmDirIfExistEmpty "${ETC_DIR}/${NX_MPKG_PACKAGE}/localhost" "cmd"

  if [ "x${NX_MPKG_PACKAGE}" != "x" ] && [ -f "${ETC_DIR}/${NX_MPKG_PACKAGE}/packages/nx${package_name}.tar.gz" ];
  then
    commandRmIfExist "${ETC_DIR}/${NX_MPKG_PACKAGE}/packages/nx${package_name}.tar.gz" "cmd"
  fi

  commandRmDirIfExistEmpty "${ETC_DIR}/${NX_MPKG_PACKAGE}/packages" "cmd"
  commandRmDirIfExistEmpty "${ETC_DIR}/${NX_MPKG_PACKAGE}" "cmd"
  commandRmDirIfExistEmpty "${ETC_DIR}/" "cmd"


  if [ ${package_name} = "webplayer" ]
  then
    commandRmIfExist "${ETC_RUNNER_CONFIG_FILE}" "cmd"
    commandRmIfExist "${ETC_RUNNER_CONFIG_FILE}.sample" "cmd"
  fi

  return 0
}

removeETCDirectory ()
{
  package_name="$1"

  if [ "x${package_name}" = "x" ];
  then
    package_name=${PACKAGE_NAME}
  fi

  if [ "x${ETC_DIR}" = "x" ];
  then
    ETC_DIR="/etc/NX"
  fi

  if [ "x${ETC_CONFIG_FILE}" = "x" ];
  then
    ETC_CONFIG_FILE="${ETC_DIR}/${NX_MPKG_PACKAGE}/localhost/${package_name}.cfg"
  fi

  __removeETCDirectory ${package_name}

  return 0
}

isInstalledProduct ()
{
#Par1 - product name, i.e. player, connect, server
  printMsgDebug "isInstalledProduct: ($1)"
  ret_isInstalledProduct=0

  case "${1}" in
    player)
        getConfigFileName ${1} ${1}
        if [ -f "${ret_getConfigFileName}" ]
        then
          ret_isInstalledProduct=1
          return 0
        else
          return 0
        fi
        ;;
    node)
        getConfigFileName ${1} ${1}
        node_cfg="${ret_getConfigFileName}"
        getConfigFileName "server" "server"
        server_cfg="${ret_getConfigFileName}"

        if [ -f "${node_cfg}" ];
        then
          if [ ! -f "${server_cfg}" ];
          then
            ret_isInstalledProduct=1
            return 0
          else
            return 0
          fi
        else
          return 0
        fi
        ;;
    server)
        getConfigFileName ${1} ${1}
        server_cfg="${ret_getConfigFileName}"

        if [ -f "${server_cfg}" ];
        then
          ret_isInstalledProduct=1
        else
          return 0
        fi
        ;;
    webplayer)
        getConfigFileName ${1} ${1}
        if [ -f "${ret_getConfigFileName}" ];
        then
          ret_isInstalledProduct=1
          return 0
        else
          return 0
        fi
        ;;
#    avc)
#        if [ -f "${NX_ROOT}/lib/libav.so" ];
#        then
#          ret_isInstalledProduct=1
#          return 0
#        else
#          return 0
#        fi
#        ;;
      *)
        return 0
        esac

  return 0
}

getProductName() {

  printMsgDebug "getProductName: (${1})"
  ret_getProductName=""

  case "${1}" in
    client)
      ret_getProductName="NoMachine Client"
      ;;
    player)
      ret_getProductName="NoMachine Player"
      ;;
    node)
      ret_getProductName="NoMachine Node"
      ;;
    server)
      ret_getProductName="NoMachine Server"
      ;;
    webplayer)
      ret_getProductName="NoMachine Cloud Server"
      ;;
    connect)
      ret_getProductName="NoMachine Connect"
      ;;
    usb)
      ret_getProductName="NoMachine USB Redirector"
      ;;
    avc)
      ret_getProductName="NoMachine Avc Connector"
      ;;
  esac

  printMsgDebug "getProductName: ${ret_getProductName}"
}

capitalizeFirst ()
{
  string0="$@"
  firstchar=${string0:0:1}
  string1=${string0:1}
  retCapitalizeFirst=`${ECHOCOMMAND} "${firstchar}" | ${TRCOMMAND} "[:lower:]" "[:upper:]"`
  retCapitalizeFirst=${retCapitalizeFirst}${string1}
}

getInstalledVersionFromBinaries ()
{
  package_name=$1
  installation_path="$2"
  version=""

  printMsgDebug "getInstalledVersionFromBinaries: ($1,$2)"

  ret_getInstalledVersionFromBinaries=0

  if [ "x${package_name}" = "x" ];
  then

    printMsgDebug "getInstalledVersion: Package name not provided."

    ret_getInstalledVersionFromBinaries=1

    return 0
  fi

  if [ "x${package_name}" = "xusb" ];
  then

    printMsgDebug "Skipping check for version of installed packages from binaries: '${package_name}'"

    ret_getInstalledVersionFromBinaries=1

    return 0
  fi

  if [ "x${installation_path}" = "x" ];
  then
    printMsgDebug "getInstalledVersion: Path not provided, assumed path: ${OLD_NX_LOCALIZATION}."

    installation_path="${OLD_NX_LOCALIZATION}"
  fi

  if [ ! -x "${installation_path}/bin/nx${package_name}" ];
  then
    printMsgDebug "getInstalledVersion: File not found: ${installation_path}/bin/nx${package_name}"

    return 0
  fi

  command_out=`"${installation_path}/bin/nx${package_name}" --version 2>/dev/null | ${HEADCOMMAND} -n 1 2>/dev/null`

  if [ "x${command_out}" != "x" ];
  then
    printMsgDebug "command_out=${command_out}"

    if [[ ${command_out} == *xpired* ]];
    then
      version="3"
      version_full="3"
      version_expired=1

      ret_getInstalledVersionFromBinaries=0
      return 0
    fi

    version=`${ECHOCOMMAND} "${command_out}" | ${SEDCOMMAND} 's/.*Version //' | ${CUTCOMMAND} -d '.' -f1`
    version_full=`${ECHOCOMMAND} "${command_out}" | ${SEDCOMMAND} 's/.*Version //' | ${CUTCOMMAND} -d '.' -f -3`
    printMsgDebug "VERSION = ${version}"
  fi

  if [ "x${version}" = "x" ];
  then
    getCfgFileVersion $package_name "${installation_path}"

    if [ "${ret_getCfgFileVersion}" != "0" ];
    then
      printMsgDebug "getInstalledVersion: Cannot determine version of: ${package_name}."

      ret_getInstalledVersionFromBinaries=1

      return 0
    else

      version=`${ECHOCOMMAND} ${cfg_version} | ${CUTCOMMAND} -d '.' -f1`
      version_full=`${ECHOCOMMAND} ${cfg_version} | ${CUTCOMMAND} -d '.' -f -3`

      if [ "x${version}" != "x" ];
      then
        version=`${EXPRCOMMAND} ${version} + 1`
        printMsgDebug "VERSION = ${version}"
        return 0
      else
        printMsgDebug  "getInstalledVersion: Bad config file version."
        ret_getInstalledVersionFromBinaries=1
        return 0
      fi
    fi
  fi

  return 0
}

isUpgrade ()
{
  #
  # Par1 - package name, i.e. client, node, server
  #

  printMsgDebug "isUpgrade: ($1)"
  ret_isUpgrade=0

  package_name=$1

  PREV_NX_PATH="${OLD_NX_LOCALIZATION}"

  getPackagePath ${package_name}

  if [ ${ret_getPackagePath} = 0 ];
  then
    PREV_NX_PATH="${ROOTDIR}"
  fi

  getInstalledVersionFromBinaries "${package_name}" "${PREV_NX_PATH}"

  if [ ${ret_getInstalledVersionFromBinaries} = 1 ];
  then
    isInstalledClient3

    if [ "x${ret_isInstalledClient3}" = "x1" ];
    then
      printMsgDebug "Detected installation of an old NX Client product"

      ret_isUpgrade=1
    fi
    return 0
  fi

  isInstalledClient3

  if [ "x${ret_isInstalledClient3}" = "x1" ];
  then
    printMsgDebug "Detected installation of an old NX Client product"

    ret_isUpgrade=1

    return 0
  fi

  printMsgDebug "VERSION (isUpgrade) = ${version}"

  if [ "x${version}" != "x" ];
  then
    if [ ${version} -le 3 ];
    then
      ret_isUpgrade=1
      return 0
    fi
  fi
  return 0
}

checkServerInstallation ()
{
  printMsgDebug "checkServerInstallation: ()"
  ret_checkServerInstallation=0

  if [ -x "${NXSHELL}" ];
  then
    outCheckServerInstallation=`"${NXSHELL}" --version  2>&1 | ${HEADCOMMAND} -n 1 2>/dev/null`
    if [ $? != 0 ];
    then
      ret_checkServerInstallation=1
      return 0
    fi
  else
    ret_checkServerInstallation=1
    return 0
  fi

  return 0
}

shutdownServer ()
{
  printMsgDebug "shutdownServer: ($1)"
  ret_shutdownServer=0

  if [ "x$1" = "x" ];
  then
    NX_SERVER_ROOT="${NX_ROOT}"
  else
    NX_SERVER_ROOT="$1"
  fi

  checkServerInstallation
  if [ ${ret_checkServerInstallation} = 0 ];
  then
    if [ "x${SETUP_SCRIPT}" != "x1" ];
    then
      if [ "x${operation_nr}" = "x" ];
      then
        operation_nr="701"
      fi
      ${ECHOCOMMAND} "NX> ${operation_nr} Shutting down: nxserver."
    else
      printMsgNoDot "Shutting down: nxserver" "cmd"
    fi

    NXServer="${NX_SERVER_ROOT}/bin/nxserver.bin"
    if [ -x "${NXServer}" ];
    then
      cmdout=`"${NXSHELL}" --shutdown`

      if [ $? != 0 ];
      then
        if [ "x${SETUP_SCRIPT}" != "x1" ];
        then
          ${ECHOCOMMAND} "NX> ${operation_nr} ERROR: Cannot shutdown nxserver."
        fi
        printMsg "Cannot shutdown nxserver" "error"
        printMsg "${cmdout}" "cmd"
        ret_shutdownServer=1
      fi
    else
      printMsg "Skipping shutdown. No nxserver file." "warn"

      ret_shutdownServer=1
    fi
  else
    printMsg "Skipping shutdown. No nxshell file." "warn"

    ret_shutdownServer=1
  fi
}

stopNXServer ()
{
  ret_stopNXServer=0

  checkServerInstallation

  if [ ${ret_checkServerInstallation} != 0 ];
  then
    printMsg "Cannot stop service: nxserver" "warn"
    printMsg "checkServerInstallation" "cmd"
    ret_stopNXServer=1

    return 0
  fi

  stopServer=`"${NXSHELL}" --stop < /dev/null 2>&1`
  result_stop=$?
  result_stop=`${ECHOCOMMAND} "${stopServer}"`

  out_msg=`${ECHOCOMMAND} "${result_stop}" | ${GREPCOMMAND} "NX> 123 Disabled service: nxserver"`

  if [ "x${out_msg}" = "x" ];
  then
    out_msg=`${ECHOCOMMAND} "${result_stop}" | ${GREPCOMMAND} "NX> .* Service: nxserver already disabled"`
  fi

  if [ "x${out_msg}" = "x" ];
  then
    if [ -f "${NXSHELL}" ];
    then
      runCommand "'${NXSHELL}' --stop" "Cannot stop NX server" "warn"
      ret_stopNXServer=${ret_runCommand}

      return 0
    else
      printMsg "Cannot stop service: nxserver" "warn"

      ret_stopNXServer=1

      return 0
    fi
  fi

  return 0
}

shutdownServerPreinstall ()
{
  printMsgDebug "shutdownServerPreinstall: ()"
  getPackagePath "server"
  if [ ${ret_getPackagePath} = 0 ];
  then
    shutdownServer "${ret_packagePath}"
  fi
}

removeSlashAtTheEnd ()
{
  dirName="$1"

  if [ "x${dirName}" != "x" ] && [ "x${dirName}" != "x/" ];
  then
    dirName=`${EXPRCOMMAND} "x${dirName}" : 'x\(.*[^/]\)'`
  fi
}

commandChown ()
{
  owner="$1"
  file="$2"
  msgType="$3"
  ret_commandChown=0

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    runCommand "${CHOWNCOMMAND} ${owner} '${file}'" "Cannot change ownership of: ${file} to: ${owner}" ${msgType}
    ret_commandChown=${ret_runCommand}
    return 0
  else
    ret_commandChown=1
    printMsg "Cannot change ownership of: ${file} to: ${owner}. Path doesn't exist" "cmd"
  fi
}

commandChownIfExist ()
{
  owner="$1"
  file="$2"
  msgType="$3"
  ret_commandChown=0

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    runCommand "${CHOWNCOMMAND} ${owner} '${file}'" "Cannot change ownership of: ${file} to: ${owner}" ${msgType}
    ret_commandChown=${ret_runCommand}
    return 0
  fi
}

commandChownR ()
{
  owner="$1"
  file="$2"
  msgType="$3"

  ret_commandChownR=0

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    runCommand "${CHOWNCOMMAND} -R ${owner} '${file}'" "Cannot change ownership of: ${file} to: ${owner}" ${msgType}
    ret_commandChownR=${ret_runCommand}
    return 0
  else
    ret_commandChownR=1
    printMsg "Cannot change ownership of: ${file} to: ${owner}. Path doesn't exist" "cmd"
  fi
}

commandChownRIfExist ()
{
  owner="$1"
  file="$2"
  msgType="$3"

  ret_commandChownR=0

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    runCommand "${CHOWNCOMMAND} -R ${owner} '${file}'" "Cannot change ownership of: ${file} to: ${owner}" ${msgType}
    ret_commandChownR=${ret_runCommand}
    return 0
  fi
}


commandChmod ()
{
  perm="$1"
  file="$2"
  msgType="$3"

  ret_commandChmod=0

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    runCommand "${CHMODCOMMAND} ${perm} '${file}'" "Cannot set permissions attributes for: ${file} to: ${perm}" ${msgType}
    ret_commandChmod=${ret_runCommand}
    return 0
  else
    ret_commandChmod=1
    printMsg "Cannot set permissions attributes for: ${file} to: ${perm}. Path doesn't exist" "cmd"
  fi
}

commandChmodR ()
{
  perm="$1"
  file="$2"
  msgType="$3"

  ret_commandChmodR=0

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    runCommand "${CHMODCOMMAND} -R ${perm} '${file}'" "Cannot set permissions attributes for: ${file} to: ${perm}" ${msgType}
    ret_commandChmodR=${ret_runCommand}
  else
    ret_commandChmodR=1
    printMsg "Cannot set permissions attributes for: ${file} to: ${perm}. Path doesn't exist" "cmd"
  fi
}

commandInstall ()
{
  owner="$1"
  group="$2"
  perm="$3"
  fileSource="$4"
  fileDest="$5"
  msgType="$6"
  ret_commandInstall=0

  if [ -f "${fileSource}" ];
  then
    runCommand "${INSTALLCOMMAND} -g ${group} -m ${perm} -o ${owner} '${fileSource}' '${fileDest}'" \
               "Cannot install file: ${fileSource}" ${msgType}
    ret_commandInstall=${ret_runCommand}
    return 0
  else
    ret_commandInstall=1
    printMsg "Cannot install: ${fileSource}. Path doesn't exist" "cmd"
  fi
}

commandBackupFile ()
{
  fileSrc="$1"
  fileSuffix="$2"
  msgType="$3"

  ret_commandBackupFile=0

  if [ -f "${fileSrc}" ];
  then
    runCommand "${CPCOMMAND} -fp '${fileSrc}' '${fileSrc}.${fileSuffix}'" "Cannot do backup of: ${fileSrc}" ${msgType}
    ret_commandBackupFile=${ret_runCommand}
    return 0
  else
    ret_commandBackupFile=1
    printMsg "Cannot do backup of: ${fileSrc}. File doesn't exist" "cmd"
  fi
}

commandBackupMvFile ()
{
  fileSrc="$1"
  fileSuffix="$2"
  msgType="$3"

  ret_commandBackupMvFile=0

  if [ -f "${fileSrc}" ];
  then
    runCommand "${CPCOMMAND} -f '${fileSrc}' '${fileSrc}.${fileSuffix}'" "Cannot do backup of: ${fileSrc}" ${msgType}
    if [ ${ret_runCommand} = 0 ];
    then
      commandRm "${fileSrc}" ${msgType}
      ret_commandBackupMvFile=${ret_commandRm}
      return 0
    fi
  else
    ret_commandBackupMvFile=1
    printMsg "Cannot do backup of: ${fileSrc}. File doesn't exist" "cmd"
  fi
}

commandCp ()
{
  fileSrc="$1"
  fileDst="$2"
  msgType="$3"

  ret_commandCp=0

  if [ -f "${fileSrc}" ];
  then
    runCommand "${CPCOMMAND} -f '${fileSrc}' '${fileDst}'" "Cannot copy: ${fileSrc} to: ${fileDst}" ${msgType}
    ret_commandCp=${ret_runCommand}
    return 0
  else
    ret_commandCp=1
    printMsg "Cannot copy: ${fileSrc} to: ${fileDst}. File doesn't exist" "cmd"
  fi

}

commandCpDir ()
{
  fileSrc="$1"
  fileDst="$2"
  msgType="$3"

  if [ "x${system}" = "macosx" ] || [ "x${system}" = "xmacosx" ];
  then
    CP_OPTION="-pRP"
  else
    CP_OPTION="-pa"
  fi

  ret_commandCpDir=0

  if [ -d "${fileSrc}" ];
  then
    runCommand "${CPCOMMAND} ${CP_OPTION} '${fileSrc}' '${fileDst}'" "Cannot copy: ${fileSrc} to: ${fileDst}" ${msgType}
    ret_commandCpDir=${ret_runCommand}
    return 0
  else
    ret_commandCpDir=1
    printMsg "Cannot copy: ${fileSrc} to: ${fileDst}. File doesn't exist" "cmd"
  fi

}

commandRestoreFile ()
{
  fileSrc="$1"
  fileSuffix="$2"
  msgType="$3"

  ret_commandRestoreFile=0

  if [ "x${fileSuffix}" = "x" ];
  then
    fileSuffix="tmp"
  fi

  if [ "x${msgType}" = "x" ];
  then
    msgType="nolog"
  fi

  fileaux="${fileSrc}.${fileSuffix}"
  commandCp "${fileaux}" "${fileSrc}" ${msgType}
  if [ "x${ret_commandCp}" = "x0" ];
  then
    commandRm "${fileaux}"  "nolog"
    ret_commandRestoreFile=${ret_commandRm}
  else
    ret_commandRestoreFile=1
  fi
}

commandChownChmod ()
{
  owner="$1"
  perm="$2"
  file="$3"
  msgType="$4"

  commandChown "${owner}" "${file}" "${msgType}"
  commandChmod "${perm}" "${file}" "${msgType}"
}

commandChownChmodIfExist ()
{
  owner="$1"
  perm="$2"
  file="$3"
  msgType="$4"

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    commandChownChmod "${owner}" "${perm}" "${file}" "${msgType}"
  fi
}

commandChownChmodSuid ()
{
  owner="$1"
  perm="$2"
  file="$3"
  msgType="$4"

  commandChownChmod "${owner}" "${perm}" "${file}" "${msgType}"
  commandChmod "u+s" "${file}" "${msgType}"
}

commandChownChmodSuidIfExist ()
{
  owner="$1"
  perm="$2"
  file="$3"
  msgType="$4"

  if [ -f "${file}" ] || [ -d "${file}" ];
  then
    commandChownChmodSuid "${owner}" "${perm}" "${file}" "${msgType}"
  fi
}

commandChownChmodGuid ()
{
  owner="$1"
  perm="$2"
  file="$3"
  msgType="$4"

  commandChownChmod "${owner}" "${perm}" "${file}" "${msgType}"
  commandChmod "g+s" "${file}" "${msgType}"
}

commandRm ()
{
  file="$1"
  msgType="$2"

  runCommand "$RMCOMMAND -f '${file}'" "Cannot remove file: ${file}" "${msgType}"
  ret_commandRm=${ret_runCommand}
}

commandRmIfExist ()
{
  file="$1"
  msgType="$2"

  ret_commandRmIfExist=0

  if [ -f "${file}" ];
  then
    commandRm "${file}" ${msgType}
    ret_commandRmIfExist=${ret_runCommand}
    return 0
  fi

  return 0
}

commandRmFiles ()
{
  file="$1"
  msgType="$2"

  runCommand "$RMCOMMAND -f '${file}'*" "Cannot remove files: ${file}*" ${msgType}
  ret_commandRmFiles=${ret_runCommand}
}

commandRmTmp ()
{
  file="$1"
  msgType="$2"

  runCommand "$RMCOMMAND -f '${file}'" "Cannot remove temporary file: ${file}" ${msgType}
  ret_commandRmTmp=${ret_runCommand}
}

commandRmTmpIfExist ()
{
  file="$1"
  msgType="$2"

  ret_commandRmTmpIfExist=0

  if [ -f "${file}" ];
  then
    commandRmTmp "${file}" ${msgType}
    ret_commandRmTmpIfExist=${ret_commandRmTmp}
  fi
}

commandRmDir ()
{
  directory="$1"
  msgType="$2"

  runCommand "${RMDIRCOMMAND} '${directory}'" "Cannot remove directory: ${directory}" ${msgType}
  ret_commandRmDir=${ret_runCommand}
}

commandRmDirIfExistEmpty ()
{
  directory="$1"
  msgType="$2"

  ret_commandRmDirIfExistEmpty=0

  if [ ! -d "${directory}" ];
  then
    return
  fi

  if [ "$(${LSCOMMAND} -1A "${directory}")" ];
  then
    return
  fi

  commandRmDir "${directory}" ${msgType}
  ret_commandRmDirIfExistEmpty=${ret_commandRmDir}
}

commandRmDirRecursively ()
{
  directory="$1"
  msgType="$2"

  runCommand "${RMCOMMAND} -fr '${directory}'" "Cannot remove recursively directory: ${directory}" ${msgType}
  ret_commandRmDirRecursively=${ret_runCommand}

}

commandMkDir ()
{
  directory="$1"
  msgType="$2"

  ret_commandMkDir=0

  if [ ! -d "${directory}" ];
  then
    runCommand "${MKDIRCOMMAND} -p '${directory}'" "Cannot create directory: ${directory}" ${msgType}
    ret_commandMkDir=${ret_runCommand}
  fi

  return 0
}

commandMv ()
{
  fileSrc="$1"
  fileDst="$2"
  msgType="$3"

  if [ -f "${fileSrc}" ];
  then
    runCommand "${MVCOMMAND} '${fileSrc}' '${fileDst}'" "Cannot move file: ${fileScr} to: ${fileDst}" ${msgType}
    ret_commandMv=${ret_runCommand}
  else
    ret_commandMv=1
    printMsg "Cannot move file: ${fileSrc} to: ${fileDst}. Source file doesn't exist" "cmd"
  fi
}

commandChcon ()
{
  selinuxContext="$1"
  file="$2"
  msgType="$3"

  ret_commandChcon=0

  if [ $SELINUX_ENABLED = 1 ];
  then
    runCommand "${CHCONCOMMAND} -t '${selinuxContext}' '${file}'" "Cannot change context for: ${file} to: ${selinuxContext}" ${msgType}
    ret_commandChcon=${ret_runCommand}
  fi

  return 0
}

commandChconR ()
{
  selinuxContext="$1"
  file="$2"
  msgType="$3"

  ret_commandChcon=0

  if [ $SELINUX_ENABLED = 1 ];
  then
    runCommand "${CHCONCOMMAND} -R -t '${selinuxContext}' '${file}'" "Cannot change context for: ${file} to: ${selinuxContext}" ${msgType}
    ret_commandChcon=${ret_runCommand}
  fi

  return 0
}

commandRestoreCon ()
{
  file="$1"
  msgType="$2"

  ret_commandRestoreCon=0

  if [ ${SELINUX_ENABLED} = 1 ];
  then
    runCommand "${RESTORECONCOMMAND} -v '${file}'" "Cannot restore selinux context for: ${file}" ${msgType}
    ret_commandRestoreCon=${ret_runCommand}
  fi

  return 0
}

commandRestoreConR ()
{
  file="$1"
  msgType="$2"

  ret_commandRestoreCon=0

  if [ ${SELINUX_ENABLED} = 1 ];
  then
    runCommand "${RESTORECONCOMMAND} -v -R '${file}'" "Cannot restore selinux context for: ${file}" ${msgType}
    ret_commandRestoreCon=${ret_runCommand}
  fi

  return 0
}

commandTouch ()
{
  file="$1"
  msgType="$2"

  if [ ! -f "${file}" ];
  then
    runCommand "${TOUCHCOMMAND} '${file}'" "Cannot create file: ${file}" ${msgType}
    ret_commandTouch=${ret_runCommand}
  else
    ret_commandTouch=0
    printMsg "Cannot create file: ${file}. File already exists" "cmd"
  fi
}

commandLn ()
{
  fileSrc="$1"
  fileDst="$2"
  msgType="$3"

  ret_commandLn=0

  if [ -f "${fileSrc}" ];
  then
    if [ ! -h "${fileDst}" ];
    then
      runCommand "${LNCOMMAND} -s '${fileSrc}' '${fileDst}'" "Cannot create symlink: ${fileSrc} to ${fileDst}" ${msgType}
      ret_commandLn=${ret_runCommand}
    else
      ret_commandLn=1
      printMsg "Cannot create symlink. Destination file already exists: ${fileDst}" "cmd"
    fi
  else
    ret_commandLn=1
    printMsg "Cannot create symlink to: ${fileDst}. Source file not found: ${fileSrc}" "cmd"
  fi
}

commandUnlink ()
{
  file="$1"
  msgType="$2"

  ret_commandUnlink=0

  if [ -f "${file}" ];
  then
    runCommand "${UNLINKCOMMAND} '${file}'" "Cannot unlink file: ${file}" ${msgType}

    ret_commandUnlink=${ret_runCommand}
  else
    ret_commandUnlink=1

    printMsg "Cannot unlink file: ${file}. File not found." "cmd"
  fi
}

commandKill ()
{
  pid=$1

  runCommand "${KILLCOMMAND} -9 '${pid}'" "Cannot kill process: ${pid}" ${msgType}

  ret_commandKill=${ret_runCommand}
}

commandKillAll ()
{
  app=$1
  msgType="$2"

  runCommand "${KILLALLCOMMAND} ${app}" "Cannot kill processes: ${app}" ${msgType}

  ret_commandKillAll=${ret_runCommand}
}

commandKillAllIfExist ()
{
  app=$1
  msgType="$2"

  ret_commandKillAllIfExist=0

  out_ps=`${PSCOMMAND} ax | ${GREPCOMMAND} "/${app} \|/${app}$" | ${GREPCOMMAND} -v grep 2>/dev/null`

  if [ "x${out_ps}" != "x" ];
  then
    commandKillAll "${app}" "${msgType}"

    ret_commandKillAllIfExist=${ret_commandKillAll}
  fi
}

getInstallPath()
{

printMsgDebug "getInstallPath: (${NX_PATH_DEFAULT},${NX_PATH_ENV},${NX_PATH_RELOCATE})"

  if [ "x${NX_PATH_DEFAULT}" = "x" ];
  then
    if [ "${system}" = "solaris" ];
    then
      NX_PATH_DEFAULT="/opt"
    else
      NX_PATH_DEFAULT="/usr"
    fi
  fi


#  if [ "x$NX_PATH_RELOCATE" != "x" ] && [ "$NX_PATH_RELOCATE" != "$NX_PATH_DEFAULT" ];
  if [ "x${NX_PATH_RELOCATE}" != "x" ];
  then
    INSTALL_PATH="${NX_PATH_RELOCATE}"
    return 0
  fi


  if [ "x${NX_PATH_ENV}" != "x" ];
  then
    INSTALL_PATH="${NX_PATH_ENV}"
    return 0
  fi

  INSTALL_PATH="${NX_PATH_DEFAULT}"
  return 0
}

getInstallationPath()
{
  printMsgDebug "getInstallationPath"
  ret_getInstallationPath=0

  removeSlashAtTheEnd "${DEFAULT_PREFIX}"
  NX_PATH_DEFAULT="${dirName}"

  removeSlashAtTheEnd "${NX_INSTALL_PREFIX}"
  NX_PATH_ENV="${dirName}"

  removeSlashAtTheEnd "${RPM_INSTALL_PREFIX0}"
  NX_PATH_RELOCATE="${dirName}"

  getInstallPath
  ret_getInstallationPath=ret_getInstallPath
}

isNewestConfFileVersion ()
{
  printMsgDebug "isNewestConfFileVersion($1)"
  ret_isNewestConfFileVersion=0

  package_name="$1"

  if [ "x${package_name}" = "x" ];
  then
    package_name="${PACKAGE_NAME}"
  fi

  getInstallationPath

  getCfgFileVersion "${package_name}" "${INSTALL_PATH}/NX"

  printMsgDebug "isNewestConfFileVersion: ${ret_getCfgFileVersion}, ${cfg_version}"

  if [ "x${cfg_version}" = "x4.0" ];
  then
    printMsgDebug "isNewestConfFileVersion: A newer config file is already installed (${ret_getConfigFileVersion})."

    ret_isNewestConfFileVersion=1
  elif [ "x${cfg_version}" = "x" ];
  then
    printMsgDebug "isNewestConfFileVersion: Cannot stat config file for installation."

    ret_isNewestConfFileVersion=1
  else
    printMsgDebug "isNewestConfFileVersion: An older config file is installed (${ret_getConfigFileVersion})."
  fi
}

isInstalledClient3 ()
{
  printMsgDebug "isInstalledClient3()"
  ret_isInstalledClient3=0

  if [ -f "${NX_ROOT}/bin/nxkill" ] || [ -f "${NX_ROOT}/bin/nxservice" ];
  then
    ret_isInstalledClient3=1
  fi

  printMsgDebug "isInstalledClient3(return ${ret_isInstalledClient3})"
}

printHelpSystemInfo ()
{
  ${ECHOCOMMAND} "The specified SYSTEM must be one of the following operating systems."
  ${ECHOCOMMAND} "If not the NoMachine setup will try to autodetect the system or will choose"
  ${ECHOCOMMAND} "the layout that better resembles one of the known OS."
  ${ECHOCOMMAND} ""
  ${ECHOCOMMAND} "       redhat       Red Hat Enterprise 4/5/6 etc."
  ${ECHOCOMMAND} "       suse         SLED 10/11/12, SLES 10/11/12, Open SUSE 10.x/11.x/12.x/13.x"
  ${ECHOCOMMAND} "       slackware"
  ${ECHOCOMMAND} "       mandriva     Mandriva 2009/2010/2011 etc."
  ${ECHOCOMMAND} "       debian       Debian GNU Linux 4.0 Etch/5.0 Lenny/6.0 Squeeze etc."
  ${ECHOCOMMAND} "                    Ubuntu 8.04 Hardy Heron/8.10 Intrepid Ibex/9.04 Jaunty Jackalope"
  ${ECHOCOMMAND} "                           9.10 Karmic Koala/10.4 Lucid Lynx/10.10 Maverick Meerkat"
  ${ECHOCOMMAND} "                           11.04 Natty Narwhal/11.10 Oneiric Ocelot etc."
  ${ECHOCOMMAND} "       fedora       Fedora 10/11/12/13/14/15/16 etc."
}

updatePathsInFile ()
{
  file="$1"
  updatePathsInFile=0

  if [ ! -f "${file}" ];
  then
    printMsg "Cannot update paths. File not found: ${file}" "cmd"
    updatePathsInFile=1
    return 0
  fi

  if [ "${NX_ROOT}" != "/usr/NX" ];
  then
    ${SEDCOMMAND} -e 's:/usr/NX:'"${NX_ROOT}"':' "${file}" > "${file}".sed
    commandMv "${file}.sed" "${file}"
  fi
}

startNXHtd()
{
  ret_startNXHtd=0

  out=`"${NXSHELL}" --restart htd`

  out_grep=`${ECHOCOMMAND} ${out} | ${GREPCOMMAND} "Enabled service.*htd"`
  if [ "x${out_grep}" != "x" ];
  then
    ret_startNXHtd=0
    return 0
  fi

  out_grep=`${ECHOCOMMAND} ${out} | ${GREPCOMMAND} ERROR`
  if [ "x${out_grep}" != "x" ];
  then
    out_grep=`${ECHOCOMMAND} $out | ${SEDCOMMAND} -e 's/NX> ... ERROR: //' 2>/dev/null`
    printMsg "${out_grep}" "cmd"
    setInstallationError
    ret_startNXHtd=1
  fi
}


startNXServer()
{
  silent_start=$1
  checkssh=$2

  if [ "x${silent_start}" = "x" ];
  then
    silent_start=0
  fi

  ret_startNXServer=0

  if [ "x${silent_start}" = "x0" ];
  then
    if [ "x${SKIP_START_SERVER}" = "x1" ];
    then
      printMsg "Skipping start service: nxserver because of previous errors" "warn"

      ret_startNXServer=1

      return 0
    fi

    if [ "x${NX_MPKG_PACKAGE}" = "xplayer" ];
    then
      printMsg "Starting service: nxserver"
    fi
  fi

  checkServerInstallation
  if [ ${ret_checkServerInstallation} != 0 ];
  then
    if [ "x${silent_start}" = "x0" ];
    then
      if [ "x${SETUP_SCRIPT}" != "x1" ];
      then
        ${ECHOCOMMAND} "NX> 701 ERROR: Cannot start service: nxserver"
      else
        printMsg "Cannot start service: nxserver" "error"
      fi

      SKIP_START_SERVER=1
    fi

    ret_startNXServer=1
    return 0
  fi

  if [ "x${checkssh}" = "xcheckssh" ] || [ "x${ONLYCHECKSSH}" != "x" ];
  then
    runCommand "'${NXSHELL}' --checkssh" "Cannot check SSH server keys" "cmd"

    if [ ${ret_runCommand} = 0 ];
    then
      ret_startNXServer=0
    else
      ret_startNXServer=1
    fi

    return 0

  else
    initSystem=""

    if [ -f /proc/1/comm ];
    then
      initSystem=`${CATCOMMAND} /proc/1/comm`
    fi

    if [[ "x${initSystem}" = "xsystemd" ]]; 
    then
      runCommand "${SYSTEMCTLCOMMAND} restart nxserver.service" "Cannot enable systemd service: $1" "error"
    else
      runCommand "'${NXSHELL}' --startup" "Cannot start NX server" "cmd"
    fi
  fi

  if [ "x${outCommand}" = "x" ];
  then
    ret_startNXServer=0
    return 0
  fi

  out_msg=`${ECHOCOMMAND} "${outCommand}" | ${GREPCOMMAND} "NX> 122 Enabled service: nxserver"`
  if [ "x${out_msg}" != "x" ];
  then
    ret_startNXServer=0
    return 0
  fi

  out_msg=`${ECHOCOMMAND} "${outCommand}" | ${GREPCOMMAND} "NX> 500 Service: nxserver already enabled"`
  if [ "x${out_msg}" != "x" ];
  then
    ret_startNXServer=0
    return 0
  fi

  out_msg=`${ECHOCOMMAND} "${outCommand}" | ${GREPCOMMAND} "NX> 500 .*NX access is disabled"`
  if [ "x${out_msg}" != "x" ];
  then
    ret_startNXServer=0
    return 0
  fi

  out_msg=`${ECHOCOMMAND} "${outCommand}" | ${GREPCOMMAND} "NX> 500 .*Cannot start service.*nxserver"`
  if [ "x${out_msg}" != "x" ];
  then
    out_msg=`${ECHOCOMMAND} "${outCommand}" | ${SEDCOMMAND} -e 's|ERROR: ||' | ${SEDCOMMAND} -e 's|^NX> [[:digit:]]\{3\} |NX> '$PROCESS' ERROR: |g' -e '/NX>.*Bye\..*/d'`

    if [ "x${silent_start}" = "x0" ];
    then
      ${ECHOCOMMAND} "${out_msg}"
      setInstallationError

      SKIP_START_SERVER=1
    fi

    ret_startNXServer=1
    return 0
  fi

  if [ $ret_runCommand != 0 ];
  then
    if [ "x${silent_start}" = "x0" ];
    then
      if [ "x${SETUP_SCRIPT}" != "x1" ];
      then
        ${ECHOCOMMAND} "NX> 701 ERROR: Cannot start service: nxserver"
      else
        printMsg "Cannot start service: nxserver" "warn"
      fi

      SKIP_START_SERVER=1
    fi

    ret_startNXServer=1
  fi

  return 0
}

getArchOfFile ()
{
  file=$1

  #0 - 32-bit;   1 - 64-bit;   2 - unknown
  ret_getArchOfFile=2

  if [ ! -e "$file" ];
  then
    ret_getArchOfFile=2
    return 0
  fi

  out=`${OBJDUMPCOMMAND} -f "$file" 2>/dev/null | ${GREPCOMMAND} ^architecture`
  if [ "x${out}" != "x" ];
  then
    out_grep=`${ECHOCOMMAND} "$out" | ${GREPCOMMAND} "x86.64"`
    if [ "x${out_grep}" != "x" ];
    then
      ret_getArchOfFile=1
      return 0
    fi

    out_grep=`${ECHOCOMMAND} "$out" | ${GREPCOMMAND} "i.86"`
    if [ "x${out_grep}" != "x" ];
    then
      ret_getArchOfFile=0
      return 0
    fi

  fi

  return 0
}

initializeLogFile ()
{
  if [ "x$1" = "x" ];
  then
    if [ "x${LOGFILE}" = "x" ];
    then
      LOGFILE="${UPDATELOG}"
    fi
  else
    LOGFILE="${1}"
  fi

  createLogdirectory
  startLog
}

isServerInstalled ()
{
  if [ -f "${SERVER_USR_CONFIG_FILE}" ];
  then
    ret_isServerInstalled=1
    return 0
  fi

  ret_isServerInstalled=0
  return 0
}

isPackageInstalled ()
{
  package_name="$1"

  getConfigFileName "webplayer"

  if [ -f "${ret_getConfigFileName}" ]
  then
    ret_isWebPlayerInstalled=1
    return 0
  fi

  ret_isWebPlayerInstalled=0
  return 0
}

canInstall ()
{
  #
  # Par1 - product name, i.e. player, node, server, webplayer
  #

  printMsgDebug "canInstall: ($1)"

  productName="${1}"
  ret_canInstall=1

  if [ "${productName}" = "server" ];
  then
    isInstalledProduct "player"

    if [ ${ret_isInstalledProduct} = 1 ];
    then
      getProductName "player"

      ret_canInstall=0
    else
      isInstalledProduct "node"

      if [ ${ret_isInstalledProduct} = 1 ];
      then
        getProductName "node"

        ret_canInstall=0
      fi
    fi

  elif [ "${productName}" = "node" ];
  then
    isInstalledProduct "server"

    if [ ${ret_isInstalledProduct} = 1 ];
    then
      getProductName "server"

      ret_canInstall=0
    else
      isInstalledProduct "player"

      if [ ${ret_isInstalledProduct} = 1 ];
      then
        getProductName "player"

        ret_canInstall=0
      fi
    fi

  elif [ "${productName}" = "player" ];
  then
    isInstalledProduct "server"

    if [ ${ret_isInstalledProduct} = 1 ];
    then
      getProductName "server"

      ret_canInstall=0
    else
      isInstalledProduct "node"

      if [ ${ret_isInstalledProduct} = 1 ];
      then
        getProductName "node"

        ret_canInstall=0
      fi
    fi
  fi

  if [ ${ret_canInstall} = 0 ];
  then
    ${ECHOCOMMAND} "Detected installation of $ret_getProductName package."

    return 0
  fi

  requireOtherPackages=0

  if [ "${productName}" = "webplayer" ];
  then
    isInstalledProduct "server"
    if [ ${ret_isInstalledProduct} = 0 ];

    then
      getProductName "webplayer"

      ${ECHOCOMMAND} "To install the $ret_getProductName, please be sure you have already"
      ${ECHOCOMMAND} "installed a NoMachine package to make this host a server."

      ret_canInstall=0
    fi

    return 0
  elif [ "${productName}" = "usb" ];
  then
    isInstalledProduct "server"

    if [ ${ret_isInstalledProduct} = 0 ];
    then
      isInstalledProduct "player"

      if [ ${ret_isInstalledProduct} = 0 ];
      then
        requireOtherPackages=1
      fi
    fi

    if [ ${requireOtherPackages} = 1 ];
    then
      ${ECHOCOMMAND} "NoMachine USB software can work only together with the NoMachine"
      ${ECHOCOMMAND} "software: install a NoMachine client on client side and any"
      ${ECHOCOMMAND} "of the NoMachine servers on server side."

      ret_canInstall=0
    fi
  elif [ "${productName}" = "avc" ];
  then
    isInstalledProduct "server"

    if [ ${ret_isInstalledProduct} = 0 ];
    then
      getProductName "avc"

      ${ECHOCOMMAND} "To install the $ret_getProductName, please be sure you have already"
      ${ECHOCOMMAND} "installed a NoMachine package to make this host a server."

      ret_canInstall=0
    fi

    return 0
  fi
}


canUninstall ()
{
  package_name="$1"

  ret_canUninstall=1

  if [ "x${package_name}" = "xserver" ];
  then
    isInstalledProduct "webplayer"

    if [ ${ret_isInstalledProduct} = 1 ];
    then
      getProductName "webplayer"

      ret_canUninstall=0

      if [ ${ret_canUninstall} = 0 ];
      then
        ${ECHOCOMMAND} "To uninstall NoMachine, please be sure to uninstall the ${ret_getProductName} software and then retry"

        return 0
      fi
    fi

    isInstalledProduct "avc"

    if [ ${ret_isInstalledProduct} = 1 ];
    then
      getProductName "avc"

      ret_canUninstall=0

      if [ ${ret_canUninstall} = 0 ];
      then
        ${ECHOCOMMAND} "To uninstall NoMachine, please be sure to uninstall the $ret_getProductName software and then retry"

        return 0
      fi
    fi

    return 0
  fi
}

installAvc ()
{
  if [ ! -d /etc/NX ];
  then
    commandMkDir "/etc/NX"
    removeETCNX=1
  fi

  preparePackageAtPostInstall ${PACKAGE_NAME} ${PACKAGE_NAME} ${operation}

  INSTALL_PATH="/usr"
  NX_ROOT="${INSTALL_PATH}/NX"

  copyInstallationFilesFromTmp "${TMP_UNPACK_FOLDER}/NX" "${INSTALL_PATH}"

  if [ -f "${NX_ROOT}/codec/etc/codec.lic.sample" ];
  then

    if [ -f "${NX_ROOT}/codec/etc/codec.lic" ];
    then

      commandMv "${NX_ROOT}/codec/etc/codec.lic" "${NX_ROOT}/codec/etc/codec.lic.backup"
      commandChownChmod "root:${ROOTGNAME}" "0400" "${NX_ROOT}/codec/etc/codec.lic.backup"

    fi

    commandMv "${NX_ROOT}/codec/etc/codec.lic.sample" "${NX_ROOT}/codec/etc/codec.lic"
  fi

  commandChownChmod "root:${ROOTGNAME}" "0400" "${NX_ROOT}/codec/etc/codec.lic"

  if [ "x${removeETCNX}" = "x1" ] || [ ! "$(${LSCOMMAND} -1A /etc/NX)" ];
  then
    commandRmDirIfExistEmpty "/etc/NX"
  fi
}

removePackageFiles ()
{
  if [ "x${PACKAGE_NAME}" = "xavc" ];
  then
    commandRm "${NX_ROOT}/codec/lib/libav.so"
    commandRm "${NX_ROOT}/codec/lib/libx264.so"
    commandRmDirIfExistEmpty "${NX_ROOT}/codec/lib"

    commandMv "${NX_ROOT}/codec/etc/codec.lic" "${NX_ROOT}/codec/etc/codec.lic.backup"
    commandChownChmod "root:${ROOTGNAME}" "0400" "${NX_ROOT}/codec/etc/codec.lic.backup"

    commandRmDirRecursively "${NX_ROOT}/codec/share"
  fi
}

uninstall3 ()
{
  canUninstall3

  if [ ${ret_canUninstall3} = 0 ];
  then
    return 0
  fi

  isInstalled_3 "1"
  if [ ${ret_isInstalled_3} != 0 ] || [ ! -d /etc/NX ];
  then
    if [ -x /usr/NX/scripts/setup/nxmanager ];
    then
      /usr/NX/scripts/setup/nxmanager --uninstall
    fi

    if [ -x /usr/NX/scripts/setup/nxserver ];
    then
      /usr/NX/scripts/setup/nxserver --uninstall
    fi

    if [ -x /usr/NX/scripts/setup/nxnode ];
    then
      /usr/NX/scripts/setup/nxnode --uninstall
    fi

    #
    # Remove nxclient 3.X.
    #

    commandRmDirRecursively "/usr/NX/bin"
    commandRmDirRecursively "/usr/NX/lib"
    commandRmDirRecursively "/usr/NX/scripts"
    commandRmDirRecursively "/usr/NX/share"
  fi
}

canUninstall3 ()
{
  package_name="$1"
  ret_canUninstall3=1


  if [ "x${package_name}" = "x" ];
  then
    package_name="${PACKAGE_NAME}"
  fi

  if [ "x${package_name}" = "xserver" ];
  then

    #
    # nxserver package can be installed over any package 3.X
    #

    ret_canUninstall3=1
    return 0
  fi


  if [ "x${package_name}" = "xnode" ];
  then

    #
    # nxnode package can not be installed over nxserver 3.X
    #

    if [ ! -d /etc/NX ] && [ -f /usr/NX/etc/server.lic ];
    then
      ${ECHOCOMMAND} "Software can be upgraded by a package that contains the same software."

      ret_canUninstall3=0
      exit 0
    fi
  fi


  if [ "x${package_name}" = "xplayer" ];
  then

    #
    # nxplayer package can not be installed over nxserver and nxnode 3.X
    #

    if [ ! -d /etc/NX ]
    then
      if [ -f /usr/NX/etc/node.lic ] || [ -f /usr/NX/etc/server.lic ];
      then
        ${ECHOCOMMAND} "Software can be upgraded by a package that contains the same software."

        ret_canUninstall3=0
        exit 0
      fi
    fi
  fi

}

getLicenseAcronym ()
{
  license_file="$1"

  ret_getLicenseAcronym=""

  default_lic=1
  if [ "x${license_file}" != "x" ];
  then
    default_lic=0
  fi

  if [ "x${LICENSE_ACRONYM}" != "x" ] && [ ${default_lic} = 1 ];
  then
   # When already set for default license
   return 0
  fi

  if [ "x${license_file}" = "x" ];
  then

    if [ "x${LICENSE_FILE}" != "x" ];
    then

      if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
      then
        license_file="${NX_ROOT}/etc/node.lic"
      else
        license_file="${LICENSE_FILE}"
      fi

    else
      if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
      then
        license_file="${NX_ROOT}/etc/node.lic"
      else
        license_file="${NX_ROOT}/etc/server.lic"
      fi

    fi
  fi

  if [ -f "${license_file}" ];
  then
    file_lic="${license_file}"

  elif [ -f "${license_file}.sample" ];
  then
    file_lic="${license_file}.sample"

  else
    printMsg "Cannot find license file to retrieve product type" "warn"

    return 0
  fi

  ret_getLicenseAcronym=`${AWKCOMMAND} '/^Product Id/ {print $3}' "${file_lic}"`

  if [ "x${ret_getLicenseAcronym}" = "x" ];
  then
    printMsg "Error while reading product type from license file: ${file_lic}" "warn"

    return 0
  fi

  if [ ${default_lic} = 1 ];
  then

    #
    # Set global LICENSE_ACRONYM variable only in case of reading default license file.
    #

    LICENSE_ACRONYM=${ret_getLicenseAcronym}
  fi
}

licenseTypeFromAcronym ()
{
  if [ "${1}" = Ux ]; then
    NOMACHINE_LICENSE_POSTFIX=" Update"
  elif [ "${1}" = Ex ]; then
    NOMACHINE_LICENSE_POSTFIX=" Evaluation"
  elif [ "${1}" = Sx ]; then
    NOMACHINE_LICENSE_POSTFIX=" Subscription"
  elif [ "${1}" = PSx ]; then
    NOMACHINE_LICENSE_POSTFIX=" Premium Subscription"
  else
    NOMACHINE_LICENSE_POSTFIX=""
  fi
}

serverVersionFromAcronym ()
{
  ACTUAL_LICENSE_ACRONYM="${1}"
  POSTFIX_TAB=("x" "Ux" "Ex" "Sx" "PSx")
  NOMACHINE_LICENSE_POSTFIX=""
  for i in ${POSTFIX_TAB[@]}; do
    licenseTypeFromAcronym $i
    if [ "${ACTUAL_LICENSE_ACRONYM}x" = "LS${i}" ]; then
      NOMACHINE_EXTENSION="${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LED${i}" ]; then
      NOMACHINE_EXTENSION=" Enterprise Desktop${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LES${i}" ]; then
      NOMACHINE_EXTENSION=" Enterprise Server${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LTS${i}" ]; then
      NOMACHINE_EXTENSION=" Terminal Server${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LSBS${i}" ]; then
      NOMACHINE_EXTENSION=" Small Business Server${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LW${i}" ]; then
      NOMACHINE_EXTENSION=" Workstation${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LEN${i}" ]; then
      NOMACHINE_EXTENSION=" Enterprise Node${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LTSN${i}" ]; then
      NOMACHINE_EXTENSION=" Terminal Server Node${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LP${i}" ]; then
      NOMACHINE_EXTENSION=" Pro${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LQS${i}" ]; then
      NOMACHINE_EXTENSION=" Quick Server${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LCS${i}" ]; then
      NOMACHINE_EXTENSION=" Cloud Server${NOMACHINE_LICENSE_POSTFIX}"
      break
    fi
  done
}

checkInstallationPathPermissions ()
{
  initial=`"${PWDCOMMAND}"`
  actual="${INSTALL_PATH}"

  while [ ! -d "${actual}" ]
  do
    if [[ -L "${actual}" && -d "${actual}" ]]
    then
      actual="${actual}/"
    else
      actual=`"${ECHOCOMMAND}" ${actual%/*}`
    fi
  done
  
  cd "${actual}"

  while [ "${actual}x" != "/x" ]
  do
    cd ..

    dirperms=`"${LSCOMMAND}" -ld "${actual}/"`
    dirperms=`"${ECHOCOMMAND}" "${dirperms}" | "${CUTCOMMAND}" -d " " -f 1`

    if [ `"${ECHOCOMMAND}" ${dirperms:4:1}` != "r" ] || \
       [ `"${ECHOCOMMAND}" ${dirperms:6:1}` != "x" ] || \
       [ `"${ECHOCOMMAND}" ${dirperms:7:1}` != "r" ] || \
       [ `"${ECHOCOMMAND}" ${dirperms:9:1}` != "x" ]
    then
      printMsg "It seems that you are trying to install this package in a directory without proper permissions. Please try to install it in a different" 0
      printMsg "directory or change permissions. The installation directory should" 0
      printMsg "have at least 555 permissions set." 0

      exit 1
    fi

    actual=`"${PWDCOMMAND}"`

  done

  cd "${initial}"
}

checkLicenseExpirationDate ()
{
  if [ -x ${NXSHELL} ] && [ -f ${NX_ROOT}/bin/nxserver.bin ]; then
    checkStr=`"${NXSHELL}" --upgradecheck`
    if [[ `${ECHOCOMMAND} "${checkStr}" | "${GREPCOMMAND}" "expired"` ]]; then
      printMsgInstall "Sorry, your upgrade period has expired. To be able to" 0
      printMsgInstall "install a new version of the software, please visit the" 0
      printMsgInstall "NoMachine Web site at http://www.nomachine.com/" 0
      printMsgInstall "to acquire a valid subscription." 0
      exit 1
    fi
  fi
}

updateOnlyIfServerIsTheSame ()
{
  if [ -f "${NX_ROOT}/etc/DisableBlockingScript" ]; then
    rm "${NX_ROOT}/etc/DisableBlockingScript"
    return 0
  fi
  if [ -f "${NX_ROOT}/bin/nxserver.bin" ]; then
    if [ -f "${NX_ROOT}/etc/server.lic" ]; then
      getLicenseAcronym "${NX_ROOT}/etc/server.lic"
      OLD_LICENSE_ACRONYM="${ret_getLicenseAcronym}"
      IS3INSTALLED=`grep "Product\:" "${NX_ROOT}/etc/server.lic"`
      LICENSE3_TYPE="${NX_ROOT}/etc/server.lic"
    elif [ -f "${NX_ROOT}/etc/node.lic" ]; then
      getLicenseAcronym "${NX_ROOT}/etc/node.lic"
      OLD_LICENSE_ACRONYM="${ret_getLicenseAcronym}"
      IS3INSTALLED=`grep "Product\:" "${NX_ROOT}/etc/node.lic"`
      LICENSE3_TYPE="${NX_ROOT}/etc/node.lic"
    else
      return 0
    fi
  else
    return 0
  fi
  if [ "x${OLD_LICENSE_ACRONYM}" = "x" ]; then
    return 0
  fi
  if [[ "${IS3INSTALLED}x" = *NX*x ]]; then
    if [[ "${IS3INSTALLED}x" = *NX\ Small\ Business\ Server*x ]]; then
      LIC_PSTFIX=`echo $OLD_LICENSE_ACRONYM | cut -c5-`
      OLD_LICENSE_ACRONYM="LSBS${LIC_PSTFIX}"
    elif [[ "${IS3INSTALLED}x" = *NX\ Free\ Edition*x ]]; then
      LIC_PSTFIX=`echo $OLD_LICENSE_ACRONYM | cut -c4-`
      OLD_LICENSE_ACRONYM="LS${LIC_PSTFIX}"
    elif [[ "${IS3INSTALLED}x" = *NX\ Enterprise\ Server*x ]]; then
      LIC_PSTFIX=`echo $OLD_LICENSE_ACRONYM | cut -c4-`
      OLD_LICENSE_ACRONYM="LTS${LIC_PSTFIX}"
    elif [[ "${IS3INSTALLED}x" = *NX\ Enterprise\ Desktop*x ]]; then
      LIC_PSTFIX=`echo $OLD_LICENSE_ACRONYM | cut -c5-`
      OLD_LICENSE_ACRONYM="LW${LIC_PSTFIX}"
    elif [[ "${IS3INSTALLED}x" = *NX\ Advanced\ Server*x ]]; then
      if [[ "${IS3INSTALLED}x" = *Node*x ]]; then
        LIC_PSTFIX=`echo $OLD_LICENSE_ACRONYM | cut -c5-`
        OLD_LICENSE_ACRONYM="LTSN${LIC_PSTFIX}"
      else
        LIC_PSTFIX=`echo $OLD_LICENSE_ACRONYM | cut -c4-`
        OLD_LICENSE_ACRONYM="LES${LIC_PSTFIX}"
      fi
    fi
    if [ "x${LIC_PSTFIX}" = "x" ]; then
      ${GREPCOMMAND} "Evaluation" "${LICENSE3_TYPE}" > /dev/null && OLD_LICENSE_ACRONYM="${OLD_LICENSE_ACRONYM}E"
    fi
  fi
  if [[ "${OLD_LICENSE_ACRONYM}" = "LPSE" ]]; then
    OLD_LICENSE_ACRONYM="LCSE"
  elif [[ "${OLD_LICENSE_ACRONYM}" = "LPSS" ]]; then
    OLD_LICENSE_ACRONYM="LCSS"
  elif [[ "${OLD_LICENSE_ACRONYM}" = "LPSPS" ]]; then
    OLD_LICENSE_ACRONYM="LCSPS"
  fi
  if [ "${NEW_LICENSE_ACRONYM}" = "${OLD_LICENSE_ACRONYM}" ]; then
    return 0
  elif [ "${NEW_LICENSE_ACRONYM}" != "${OLD_LICENSE_ACRONYM}" ]; then
    NEW_LICENSE_ACRONYM_SED=`${ECHOCOMMAND} "${NEW_LICENSE_ACRONYM}" | ${SEDCOMMAND} s'/.$//'`
    if [ "${NEW_LICENSE_ACRONYM: -1}" = "U" ]; then
      if [ "${NEW_LICENSE_ACRONYM_SED}E" = "${OLD_LICENSE_ACRONYM}" ] || [ "${NEW_LICENSE_ACRONYM_SED}S" = "${OLD_LICENSE_ACRONYM}" ] || [ "${NEW_LICENSE_ACRONYM_SED}PS" = "${OLD_LICENSE_ACRONYM}" ] || [ "${NEW_LICENSE_ACRONYM_SED}" = "${OLD_LICENSE_ACRONYM}" ]; then
        return 0
      fi
    fi

    serverVersionFromAcronym "${OLD_LICENSE_ACRONYM}"
    INSTALLED_NOMACHINE="${NOMACHINE_EXTENSION}"
    serverVersionFromAcronym "${NEW_LICENSE_ACRONYM}"
    NEW_NOMACHINE="${NOMACHINE_EXTENSION}"

    printMsgInstall "NoMachine${INSTALLED_NOMACHINE} appears to be installed on this host. Two" 0
    printMsgInstall "different NoMachine packages can't be installed at the same time on" 0
    printMsgInstall "the same host. Be sure you uninstall NoMachine${INSTALLED_NOMACHINE} before" 0
    printMsgInstall "installing NoMachine${NEW_NOMACHINE}. " 0

    exit 1
  fi
}

blockAloneUpdatePackageInstallation ()
{
  lastChar=`${ECHOCOMMAND} -n "${NEW_LICENSE_ACRONYM}" | ${TAILCOMMAND} -c1`

  if [ "x${lastChar}" = "xU" ] && 
     [ ! -f "${NX_ROOT}/bin/nxserver.bin" ];
  then
    printMsgInstall "You cannot use a package for update to perform a new fresh installation." 0

    exit 1
  fi
}

backupNodesDatabaseForServer3Upgrade ()
{
  #
  # Upgrade procedure from NX Advanced Server
  # will remove nodes.db. We have to preserved
  # original file.
  #

  getLicenseAcronym "${NX_ROOT}/etc/server.lic"
  base_lic_acronym="${ret_getLicenseAcronym}"

  if [ "x${base_lic_acronym}" = "xLASS" ];
  then
    commandBackupFile "${NX_ROOT}/etc/nodes.db" "backup" "warn"
  fi
}

backupVersionFile ()
{
  if [ -f "${NX_ROOT}/etc/version" ];
  then
    commandBackupFile "${NX_ROOT}/etc/version" "backup" "warn"
  fi
}

addUpdateDBFile ()
{
  #
  # 1 - for others.
  # 2 - for node packages.
  #

  if [ "$system" = "macosx" ]; then
    var_db="/Library/Application Support/NoMachine/var/db/"
  else
    var_db="${NX_ROOT}/var/db/"
  fi

  if [ ! -d "${var_db}" ]; then
    runCommand "${MKDIRCOMMAND} -p '${var_db}'" "Cannot create directory: '${var_db}'" "error"
  fi

  if [ ! -f "${var_db}/update" ]; then
    runCommand "${TOUCHCOMMAND} '${var_db}/update'" "Cannot create ${var_db}/update file" "error" 
  fi

  commandChmod "0666" "${var_db}/update" "warn"
}



MSG_ERROR_OWNERSHIP="Cannot change ownership for"
MSG_ERROR_PERMISSIONS="Cannot change permissions for"

parCount=$#

LastCommand=""

CUPS_PATH=(/usr /opt/sfw/cups /usr/local /usr/lib /usr/lib64 /opt/csw /usr/libexec)
CUPS_CERTS_DIR=(/var/run/cups/certs /var/lib/cups/certs /etc/cups/certs)

NXFUNCTSH="${NX_ROOT}/scripts/restricted/nxfunct.sh"
NXPRINT="${NX_ROOT}/bin/nxprint"
WRAPPER="${NX_ROOT}/bin/nxexec"

NX_PAM_SCRIPT="${NX_ROOT}/scripts/etc/pam.d/nx"
NX_PAM_SCRIPT_LIMITS="${NX_ROOT}/scripts/etc/pam.d/nxlimits"

NX_XDG="${NX_ROOT}/share/applnk/${PACKAGE_NAME}/xdg"

DEFAULT_NXD_PORT="4000"

createLogdirectory ()
{
  if [ ! -d "${NX_VAR_DIR}/log" ];
  then
    command="${MKDIRCOMMAND} -p '${NX_VAR_DIR}/log'"
    outCommand=`${BASHSHELL} -c "$command" 2>&1`

    if [ $? != 0 ];
    then
      LOGFILE=""

      printMsg "Cannot create log directory: ${NX_VAR_DIR}/log" "warn"
      printMsg "All information is being redirected to stdout" "warn"
    else
      commandChmod "1777" "${NX_VAR_DIR}/log" "warn"
    fi
  else
    commandChmod "1777" "${NX_VAR_DIR}/log" "warn"
  fi
}

startLog () {

  if [ -f "$LOGFILE" ];
  then
    command="${ECHOCOMMAND} ' ' >> '$LOGFILE'"
  else
    command="${ECHOCOMMAND} ' ' > '$LOGFILE'"
  fi

  outCommand=`${BASHSHELL} -c "$command" 2>&1`

  if [ "$?" != 0 ];
  then
    tmp="$LOGFILE"
    LOGFILE=""

    printMsg "Cannot create logfile: $tmp:" "warn"
    printMsg "'$outCommand'" "warn"
    printMsg "All information is being redirected to stdout" "warn"
  fi

  if [ "$LOGFILE" != "" ];
  then
    command="${ECHOCOMMAND} '' | ${TEECOMMAND} -a '$LOGFILE' 2>&1"
    outCommand=`${BASHSHELL} -c "$command" 2>&1`
    if [ "$?" != 0 ];
    then
      tmp="$INSTALLOG"
      LOGFILE=""

      printMsg "Cannot initialize log file: $tmp:" "warn"
      printMsg "Command: '$command'" "warn"
      printMsg "'$outCommand'" "warn"
      printMsg "All information is being redirected to stdout" "warn"
    fi
  fi
}

printMsgUpdateEntriesInConfigFile ()
{
  printMsg "Updating ${1} entries in: ${CONFIG_FILE}" "cmd"
}

printMsgAddKeyToConfigFile ()
{
  if [ "x$2" != "x" ];
  then
    if [ "$2" = "\"\"" ];
    then
      printMsg "Added key '$1=\"\"' to config file" "cmd"
    else
      printMsg "Added key '$1=\"$2\"' to config file" "cmd"
    fi
  else
    printMsg "Added key '$1' to config file" "cmd"
  fi
}

printMsgRemoveKeyFromConfigFile ()
{
  printMsg "Removed key: ${1}" "cmd"
}

printMsgUpdatedKeyinConfigFile ()
{
  printMsg "Updated key: $1=\"$2\"" "cmd"
}

printMsgRenamedKeyinConfigFile ()
{
  printMsg "Renamed key: ${1} to ${2}" "cmd"
}

INSTALL_WARNING_FILE="${NX_ROOT}/.warning"
INSTALL_ERROR_FILE="${NX_ROOT}/.error"

setInstallationWarning ()
{
  if [ ! -f "${INSTALL_WARNING_FILE}" ] && [ ! -f "${INSTALL_ERROR_FILE}" ];
  then
    commandTouch "${INSTALL_WARNING_FILE}" "nolog"
  fi
}

remInstallationWarning ()
{
  if [ -f "${INSTALL_WARNING_FILE}" ];
  then
    commandRm "${INSTALL_WARNING_FILE}" "nolog"
  fi
}

setInstallationError ()
{
  if [ ! -f "${INSTALL_ERROR_FILE}" ];
  then
    commandTouch "${INSTALL_ERROR_FILE}" "nolog"
  fi

  remInstallationWarning
}

remInstallationError ()
{
  if [ -f "${INSTALL_ERROR_FILE}" ];
  then
    commandRm "${INSTALL_ERROR_FILE}" "nolog"
  fi
}

getInstallationStatus ()
{
  #return values
  #0 - no errors and warnings
  #1 - with errors
  #2 - with warnings

  ret_getInstallationStatus=0

  if [ -f "${INSTALL_ERROR_FILE}" ];
  then
    ret_getInstallationStatus=1
    remInstallationError
    remInstallationWarning
    return 0
  fi

  if [ -f "${INSTALL_WARNING_FILE}" ];
  then
    ret_getInstallationStatus=2
    remInstallationWarning
    return 0
  fi
}

getCurrentInstalledVersion ()
{
  package_name=$1
  if [ "x$package_name" = "x" ];
  then
    package_name=${PACKAGE_NAME}

  fi

  full_version=""
  cmd_version_2_and_3="/usr/NX/bin/nx$package_name --version"
  cmd_version_4="/etc/NX/nx$package_name --version"

  cmd_out=`"$cmd_version_4" 2>/dev/null | ${HEADCOMMAND} -n 1 2>/dev/null`

  if [ "x$cmd_out" = "x" ];
  then
    cmd_out=`"$cmd_version_2_and_3" 2>/dev/null | ${HEADCOMMAND} -n 1 2>/dev/null`
  fi
  if [ "x$cmd_out" != "x" ];
  then
    full_version=`${ECHOCOMMAND} "$cmd_out" | ${AWKCOMMAND} '{print $4}'`
  fi
}

getMajorVersion ()
{
  major_version=""
  full_version=$1

  if [ "x$full_version" = "x" ];
  then
    getCurrentInstalledVersion
  fi

  if [ "x$full_version" != "x" ];
  then
    major_version=`${ECHOCOMMAND} "$full_version" | $AWKCOMMAND -F "." '{print $1}'`
  fi
}

getUsrConfigFile ()
{
  package_name=$1

  ret_getUsrConfigFile=""

  path="${NX_ROOT}/etc"

    case "${package_name}" in
      "server"    ) ret_getUsrConfigFile="${path}/server.cfg";;
      "node"      ) ret_getUsrConfigFile="${path}/node.cfg";;
      "htd"       ) ret_getUsrConfigFile="${path}/htd.cfg";;
      "webplayer" ) ret_getUsrConfigFile="${path}/cloud.cfg";;
    esac
}


checkSELinuxModule ()
{
  ret_checkSELinuxModule=0

  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  if [ "x${SEMODULECOMMAND}" != "x" ] && [ -x "${SEMODULECOMMAND}" ];
  then
    printMsg "Checking if custom module: nx for SELinux is loaded" "cmd"

    out=`${SEMODULECOMMAND} -l 2>/dev/null | ${CUTCOMMAND} -f 1 | ${GREPCOMMAND} "^nx$"`

    if [ "x${out}" != "x" ];
    then
      ret_checkSELinuxModule=1
    fi
  fi
}

installSELinuxModule ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  if [ "x${system}" = "xfedora" ];
  then
    getDistroVersion 

    majorFedoraVersion=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f1)

    if [ "x${majorFedoraVersion}" = "x24" ];
    then
      NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/nx-unconfined-fedora24.pp"
    else
      NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/nx-unconfined.pp"
    fi

  else
    NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/nx-unconfined.pp"
  fi

  if [ "x${SEMODULECOMMAND}" != "x" ] && [ -x "${SEMODULECOMMAND}" ];
  then
    printMsg "Installing custom module: nx for SELinux" "cmd"

    if [ -f "${NX_SELINUX_MODULE}" ];
    then
      runCommand "${SEMODULECOMMAND} -v -i '${NX_SELINUX_MODULE}'" "${RUNCOMMAND_NO_ERROR_MESSAGE}"

      if [ "x${ret_runCommand}" != "x0" ];
      then
        NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/nx-system.pp"

        runCommand "${SEMODULECOMMAND} -i '${NX_SELINUX_MODULE}'" "Cannot install custom SELinux module" "warn"
      fi

      if [ "x${ret_runCommand}" = "x0" ];
      then
        if [ -x "${RESTORECONCOMMAND}" ];
        then
          printMsg "Restoring contexts for: /etc/NX" "cmd"

          runCommand "${RESTORECONCOMMAND} -v -R /etc/NX" "Cannot restore SELinux contexts for: /etc/NX" "warn"

          printMsg "Restoring contexts for: ${NX_ROOT}" "cmd"

          runCommand "${RESTORECONCOMMAND} -R '${NX_ROOT}'" "Cannot restore SELinux contexts for: ${NX_ROOT}" "warn"
        fi
      fi
    else
      printMsg "Custom module: nx for SELinux not found: ${NX_SELINUX_MODULE}" "warn"
    fi
  fi
}

removeSELinuxModule ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  if [ "x${SEMODULECOMMAND}" != "x" ] && [ -x "${SEMODULECOMMAND}" ];
  then
    printMsg "Removing custom module: nx for SELinux" "cmd"

    checkSELinuxModule

    if [ "x${ret_checkSELinuxModule}" = "x1" ];
    then
      runCommand "${SEMODULECOMMAND} -v -r nx" "Cannot remove custom SELinux module" "warn"
    fi
  fi
}


setSELinuxContext ()
{
  secontext="$1"
  filename="$2"

  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  if [ "x${NX_CUSTOM_MODULE}" = "x0" ];
  then
    return 0
  fi

  if [ "x${NX_CUSTOM_MODULE}" = "x" ];
  then 
    checkSELinuxModule
    NX_CUSTOM_MODULE=$ret_checkSELinuxModule;
  fi

#
# FIXME: commandRestoreCon usually returns 0
#         so commandChcon won't be executed
#
#  if [ "x${NX_CUSTOM_MODULE}" = "x1" ];
#  then
#    commandRestoreCon "${filename}" "warn"
#    if [ $ret_commandRestoreCon = 0 ];
#    then
#      return 0
#    fi
#  fi
#

  commandChcon "${secontext}" "${filename}" "warn"
}

setSELinuxContextR ()
{
  secontext="$1"
  filename="$2"

  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  if [ "x${NX_CUSTOM_MODULE}" = "x" ];
  then
    checkSELinuxModule
    NX_CUSTOM_MODULE=$checkSELinuxModule;
  fi

#
# FIXME: commandRestoreCon usually returns 0
#         so commandChcon won't be executed
#
#  if [ "x${NX_CUSTOM_MODULE}" = "x1" ];
#  then
#    commandRestoreConR "${filename}" "warn"
#    if [ $ret_commandRestoreCon = 0 ];
#    then
#      return 0
#    fi
#  fi
#

  commandChconR "${secontext}" "${filename}" "warn"
}

setContextForETC ()
{
  if [ "${PACKAGE_NAME}" = "server" ] && [ $SELINUX_ENABLED = 1 ];
  then
    if [ -x "/etc/NX/nx${PACKAGE_NAME}" ];
    then
      setSELinuxContext "bin_t" "/etc/NX/nx${PACKAGE_NAME}"
    fi
  fi
}

restoreContextForDir ()
{
  folder="$1"

  if [ -d "${folder}" ];
  then
    if [ $SELINUX_ENABLED = 1 ];
    then
      #runCommand "${RESTORECONCOMMAND} -v -R '${folder}'" "Cannot restore selinux context for: ${folder}" "warn"
      out=`${RESTORECONCOMMAND} -v -R "${folder}" 2>/dev/null`
    fi
  fi
}

restoreContextForInstalationDir ()
{
  restoreContextForDir "${NX_ROOT}"
}

getAvailableSessionKey ()
{
  printMsgDebug "getBasePackagePath: ($1)"
  ret_getAvailableSessionKey=0

  config_file=$1

  available_sessions=""

  if [ "x$config_file" = "x" ];
  then
    config_file="$CONFIG_FILE"
  fi

  if [ ! -f "$config_file" ];
  then
    printMsg "getAvailableSessionKey: Cannot find file: $config_file" "warn"
    ret_getAvailableSessionKey=1
    return 0
  fi

  getValueFromCfgFile "AvailableSessionTypes" "$config_file"

  if [ $ret_getValueFromCfgFile = 2 ];
  then
    available_sessions="$cfg_val"
    printMsg "Read key: AvailableSessionTypes='$available_sessions'" "cmd"
    return 0
  elif [ $ret_getValueFromCfgFile = 1 ];
  then
    available_sessions=""
    #printMsg "AvailableSessionTypes key commented out in: $config_file" "cmd"
    return 0
  else
    printMsg "Cannot read key: AvailableSessionTypes" "cmd"
    ret_getAvailableSessionKey=1
    return 0
  fi

  ret_getAvailableSessionKey=1
  return 0
}

updateAvailableSessionKey ()
{
  printMsgDebug "updateAvailableSessionKey: ($1,$2,$3)"
  ret_updateAvailableSessionKey=0

  avail_sess="$1"
  config_file="$2"
  package_name="$3"

  if [ "x$config_file" = "x" ];
  then
    config_file="$CONFIG_FILE"
  fi

  if [ "x$package_name" = "x" ];
  then
    package_name="${PACKAGE_NAME}"
  fi

  if [ $package_name != "server" ] && [ $package_name != "node" ];
  then
    printMsg "updateAvailableSessionKey: Key: AvailableSessionTypes can be set only for node or server" "warn"

    ret_updateAvailableSessionKey=1

    return 0
  fi

  if [ ! -w "$config_file" ];
  then
    printMsg "updateAvailableSessionKey: Cannot open file: $config_file for writting" "warn"

    ret_updateAvailableSessionKey=1

    return 0
  fi

  getAvailableSessionKey "$config_file"

  if [ $ret_getAvailableSessionKey != "0" ];
  then
    if [ "x${package_name}" = "xserver" ];
    then
      desc_ask="server"
    else
      desc_ask="host"
    fi

${ECHOCOMMAND} "
#
# Specify a list of comma-separated session types available on this
# server.
#
AvailableSessionTypes $avail_sess
"  >> "$config_file"

    return 0
  else
    changeKeyAtConfigFile "$config_file" "AvailableSessionTypes" "$avail_sess"

    ret_updateAvailableSessionKey=1

    return 0
  fi
}

checkAvailabilitySession ()
{
  keyName=$1
  ret_checkAvailabilitySession=0

  if [ "x$keyName" = "x" ];
  then
    return 0
  fi

  defaultCommand=""
  alternative_paths=""

  case $keyName in
    "DefaultDesktopCommand" )
          defaultCommand="unix-xsession-default"
          alternative_paths=(
                              "/etc/X11/Xsession"
                              "/etc/X11/xdm/Xsession"
                              "/etc/X11/xinit/Xsession"

                              "/usr/bin/gnome-session"
                              "/usr/local/bin/gnome-session"
                              "/opt/gnome/bin/gnome-session"
                              "/opt/gnome2/bin/gnome-session"

                              "/usr/bin/startkde"
                              "/usr/local/bin/startkde"
                              "/opt/kde3/bin/startkde"
                              "/opt/kde4/bin/startkde"
                              "/opt/kde4-devel/bin/startkde"
                            )
            ;;
    "CommandStartGnome" )
          defaultCommand="gnome-session"
          alternative_paths=(
                              "/usr/bin/gnome-session"
                              "/usr/local/bin/gnome-session"
                              "/opt/gnome/bin/gnome-session"
                              "/opt/gnome2/bin/gnome-session"
                            )
            ;;
    "CommandStartKDE" )
          defaultCommand="startkde"
          alternative_paths=(
                              "/usr/bin/startkde"
                              "/usr/local/bin/startkde"
                              "/opt/kde3/bin/startkde"
                              "/opt/kde4/bin/startkde"
                              "/opt/kde4-devel/bin/startkde"
                            )
            ;;
    "DefaultXSession" )
          defaultCommand="Xsession"
          alternative_paths=(
                              "/etc/X11/gdm/Xsession"
                              "/etc/X11/kdm/Xsession"
                              "/etc/X11/xdm/Xsession"
                              "/etc/X11/xinit/Xsession"
                              "/etc/X11/Xsession"
                            )
            ;;
    "CommandStartCDE" )
          defaultCommand="dtsession"
          alternative_paths=(
                              "/usr/dt/bin/dtsession"
                              "/opt/dt/bin/dtsession"
                            )
            ;;
    "CommandStartRDP" )
          defaultCommand="rdesktop"
          alternative_paths=(
                              "/usr/bin/rdesktop"
                              "/usr/local/bin/rdesktop"
                              "/opt/bin/rdesktop"
                            )
            ;;
    "CommandStartRFB" )
          defaultCommand="vncviewer"
          alternative_paths=(
                              "/usr/bin/vncviewer"
                              "/usr/local/bin/vncviewer"
                              "/opt/bin/vncviewer"
                            )
            ;;
    * )
         defaultCommand=""
            ;;
  esac

    commandOut=`${WHICHCOMMAND} $defaultCommand 2>/dev/null | ${HEADCOMMAND} -1`
    if [ ! -x "${commandOut}" ];
    then
      #printMsg "Cannot find $defaultCommand in \${PATH}" "cmd"
      for ((i=0;i<${#alternative_paths[@]};i++)); do
        if [ -x "${alternative_paths[${i}]}" ];
        then
          #printMsg "Found '$defaultCommand' at ${alternative_paths[${i}]}" "cmd"
          commandOut="${alternative_paths[${i}]}"
          ret_checkAvailabilitySession=1
          return 0
        fi
      done

      #printMsg "Cannot find executable $defaultCommand at alternative paths" "cmd"
      return 0
    fi

  ret_checkAvailabilitySession=1
  return 0
}

getAvailableSessionTypesList ()
{
  if [ "x${system}" != "xmacosx" ];
  then
    availableSessionList="unix-remote,unix-console,unix-default,unix-application,"
  else
    availableSessionList="unix-remote,"
  fi

  availableSessionList=${availableSessionList}"physical-desktop,"

  if [ "${system}" != "macosx" ];
  then
    availableSessionList=${availableSessionList}"shadow,"
  fi

  checkAvailabilitySession  "DefaultDesktopCommand"
  if [ $ret_checkAvailabilitySession = 1 ];
  then
    availableSessionList=${availableSessionList}"unix-xsession-default,"
  fi

  checkAvailabilitySession  "CommandStartGnome"
  if [ $ret_checkAvailabilitySession = 1 ];
  then
    availableSessionList=${availableSessionList}"unix-gnome,"
  fi

  checkAvailabilitySession  "CommandStartKDE"
  if [ $ret_checkAvailabilitySession = 1 ];
  then
    availableSessionList=${availableSessionList}"unix-kde,"
  fi

  checkAvailabilitySession  "DefaultXSession"
  if [ $ret_checkAvailabilitySession = 1 ];
  then
    availableSessionList=${availableSessionList}"unix-xdm,"
  fi

  checkAvailabilitySession  "CommandStartCDE"
  if [ $ret_checkAvailabilitySession = 1 ];
  then
    availableSessionList=${availableSessionList}"unix-cde,"
  fi

  checkAvailabilitySession  "CommandStartRDP"
  if [ $ret_checkAvailabilitySession = 1 ];
  then
    availableSessionList=${availableSessionList}"windows,"
  fi

  checkAvailabilitySession  "CommandStartRFB"
  if [ $ret_checkAvailabilitySession = 1 ];
  then
    availableSessionList=${availableSessionList}"vnc,"
  fi

  availableSessionList=${availableSessionList%","*}
}

getListMissingSessionTypes ()
{
  getAvailableSessionKey "${NODE_USR_CONFIG_FILE}"

  if [ "x$ret_getAvailableSessionKey" != "x0" ];
  then
    return 1
  fi

  getAvailableSessionTypesList

  IFS=',' read -a sessionsCfg <<< "${available_sessions}"
  IFS=',' read -a sessionsDetected <<< "${availableSessionList}"

  for elementDetected in "${sessionsDetected[@]}"
  do

    foundElement="0"

    for elementCfg in "${sessionsCfg[@]}"
    do
      if [ "x${elementDetected}" = "x$elementCfg" ];
      then
        foundElement="1"
      fi
    done

    if [ "x${foundElement}" = "x0" ];
    then
      listNewSessionNode="${listNewSessionNode}${elementDetected},"
    fi
  done

  getAvailableSessionKey "${SERVER_USR_CONFIG_FILE}"

  IFS=',' read -a sessionsCfg <<< "${available_sessions}"

  for elementDetected in "${sessionsDetected[@]}"
  do

    foundElement="0"

    for elementCfg in "${sessionsCfg[@]}"
    do
      if [ "x${elementDetected}" = "x$elementCfg" ];
      then
        foundElement="1"
      fi
    done

    if [ "x${foundElement}" = "x0" ];
    then
      listNewSessionServer="${listNewSessionServer}${elementDetected},"
    fi
  done

  listNewSessionServer="${listNewSessionServer%?}"

  IFS=',' read -a newSessionsServer <<< "${listNewSessionServer}"
  IFS=',' read -a newSessionsNode <<< "${listNewSessionNode}"

  listNewSession="${listNewSessionNode}"

  for elementServer in "${newSessionsServer[@]}"
  do

    foundElement="0"

    for elementNode in "${newSessionsNode[@]}"
    do
      if [ "x${elementNode}" = "x$elementServer" ];
      then
        foundElement="1"
      fi
    done

    if [ "x${foundElement}" = "x0" ];
    then
      listNewSession="${listNewSession}${elementServer},"
    fi
  done

  ret_getListMissingSessionTypes="${listNewSession%?}" 
}

addForeignNodeSessionTypes ()
{
  foreign_node_sessions_list="unix-remote,"

  getAvailableSessionKey "${NODE_USR_CONFIG_FILE}"

  new_available_sessions_types="${foreign_node_sessions_list}${available_sessions}"

  updateAvailableSessionKey "${new_available_sessions_types}" "${NODE_USR_CONFIG_FILE}"

  getAvailableSessionKey "${SERVER_USR_CONFIG_FILE}"

  new_available_sessions_types="${foreign_node_sessions_list}${available_sessions}"

  updateAvailableSessionKey "${new_available_sessions_types}" "${SERVER_USR_CONFIG_FILE}"
}

checkAvailableSessionTypes ()
{
  getListMissingSessionTypes

  if [ "x${previous_version}" != "x" ];
  then

   getPreviousVersion

   if [[ ("x${ret_getListMissingSessionTypes}" = "xunix-remote") &&\
         (("${major_version}" -lt "5") ||\
          ("${major_version}" -le "5" && "${minor_version}" -le "0" &&  "${maintenance_version}" -lt "11")) ]];
   then
     addForeignNodeSessionTypes

     ret_getListMissingSessionTypes=""
   fi
  fi
 
  if [ "x${ret_getListMissingSessionTypes}" != "x" ];
  then
    "${ECHOCOMMAND}" ""
    "${ECHOCOMMAND}" "Support for these types of sessions is available:"
    "${ECHOCOMMAND}" "${ret_getListMissingSessionTypes}"
    "${ECHOCOMMAND}" "You can enable this by running:"
    "${ECHOCOMMAND}" "${NX_ROOT}/scripts/setup/nxnode --availablesessionsetup"
    "${ECHOCOMMAND}" ""
  else
    printMsgDebug "Cannot find new types of sessions."
  fi
}

checkETCDirectory ()
{
  if [ "${system}" = "macosx" ] || [ ! -f /etc/NX/${NX_MPKG_PACKAGE}/localhost/${PACKAGE_NAME}.cfg ];
  then

    if [ "x${PACKAGE_NAME}" = "xclient" ] || [ "x${PACKAGE_NAME}" = "xwebplayer" ];
    then
      if [ ! -d /etc/NX ];
      then
        commandMkDir "/etc/NX" "error"
      fi
      commandChownChmod "root:${ROOTGNAME}" "755" "/etc/NX"

      if [ ! -d /etc/NX/${NX_MPKG_PACKAGE}/localhost ];
      then
        commandMkDir "/etc/NX/${NX_MPKG_PACKAGE}/localhost" "error"
      fi
      commandChownChmod "root:${ROOTGNAME}" "755" "/etc/NX/${NX_MPKG_PACKAGE}"
      commandChownChmod "root:${ROOTGNAME}" "755" "/etc/NX/${NX_MPKG_PACKAGE}/localhost"
    fi

    commandInstall "root" "${ROOTGNAME}" "644" "${NX_ROOT}/scripts/etc/localhost/${PACKAGE_NAME}.cfg" "/etc/NX/${NX_MPKG_PACKAGE}/localhost/"

    if [ "x${PACKAGE_NAME}" != "xclient" ] && [ "x${PACKAGE_NAME}" != "xplayer" ];
    then
      if [ "x${PACKAGE_NAME}" = "xserver" ];
      then
        commandInstall "${USER_NX}" "${ROOTGNAME}" "4555" "${NX_ROOT}/scripts/etc/nx${PACKAGE_NAME}" "/etc/NX/nxserver"
      else
        commandInstall "root" "${ROOTGNAME}" "755" "${NX_ROOT}/scripts/etc/nx${PACKAGE_NAME}" "/etc/NX/nx${PACKAGE_NAME}"
      fi
    fi

    return
  fi

  if [ "x${PACKAGE_NAME}" = "xserver" ];
  then
    commandChownChmodSuid "${USER_NX}:${ROOTGNAME}" "555" "/etc/NX/nxserver"
  fi

  if [ -f "${ETC_CONFIG_FILE}.sample" ];
  then
    commandChown "root:${ROOTGNAME}" "${ETC_CONFIG_FILE}.sample"
  fi

  commandChown "root:${ROOTGNAME}" "${ETC_CONFIG_FILE}"
}

removeETCDirectoryPersonal ()
{
  package_name="$1"

  ETC_DIR="$2"
  if [ "x${ETC_DIR}" = "x" ];
  then
    ETC_DIR="${HOME}/.nx/config/server"
  fi

  if [ "x$package_name" = "x" ];
  then
    package_name=${PACKAGE_NAME}
  fi

  ETC_CONFIG_FILE="${ETC_DIR}/${NX_MPKG_PACKAGE}/localhost/${package_name}.cfg"

  __removeETCDirectory ${package_name}

  return 0
}

cleanPackageFiles ()
{
  for ((i=0;i<${#package_files[@]};i++))
  do
    out=`${ECHOCOMMAND} "${package_files[${i}]}" | ${GREPCOMMAND} "\.\."`

    if [ $? != 0 ];
    then
      grep_out=`${ECHOCOMMAND} "${package_files[${i}]}" | ${GREPCOMMAND} "\*"`
      ret=$?

      if [ $ret=0 ];
      then
        file_aux=`${ECHOCOMMAND} "$NX_ROOT${package_files[${i}]}" | ${CUTCOMMAND} -d "*" -f1`

        file_ext=`${ECHOCOMMAND} "$NX_ROOT${package_files[${i}]}" | ${CUTCOMMAND} -d "*" -f2`

        if [ "x$file_ext" = "x" ];
        then
          runCommand "$RMCOMMAND -f '$file_aux'*" "$RUNCOMMAND_NO_ERROR_MESSAGE" "cmd"
       else
          commandRm "$NX_ROOT${package_files[${i}]}" "cmd"
        fi

      else
        commandRmIfExist "$NX_ROOT${package_files[${i}]}" "cmd"
      fi
    else
      printMsg "Cannot delete directory: $NX_ROOT${package_files[${i}]} from security reasons" "warn"
    fi
  done

  for ((i=0;i<${#package_directories_recursive_before[@]};i++))
  do
    out=`${ECHOCOMMAND} "${package_directories_recursive_before[${i}]}" | ${GREPCOMMAND} "\.\."`

    if [ $? != 0 ];
    then
      commandRmDirRecursively "$NX_ROOT${package_directories_recursive_before[${i}]}" "cmd"
    else
      printMsg "Cannot delete recursively directory: $NX_ROOT${package_directories_recursive_before[${i}]} for security reasons" "warn"
    fi
  done

  for ((i=0;i<${#package_directories_empty[@]};i++))
  do
    commandRmDirIfExistEmpty "$NX_ROOT${package_directories_empty[${i}]}" "cmd"
  done

  for ((i=0;i<${#package_directories_recursive[@]};i++))
  do
    out=`${ECHOCOMMAND} "${package_directories_recursive[${i}]}" | ${GREPCOMMAND} "\.\."`

    if [ $? != 0 ];
    then
      commandRmDirRecursively "$NX_ROOT${package_directories_recursive[${i}]}" "cmd"
    else
      printMsg "Cannot delete recursively directory: $NX_ROOT${package_directories_recursive[${i}]} for security reasons" "warn"
    fi
  done

  removeETCDirectory
}

removeOldLibrariesMac ()
{
  NX_LIB="$NX_ROOT/lib"

  for ((i=0;i<${#tab_lib_ver[@]};i++))
  do
    lib_file=`${ECHOCOMMAND} ${tab_lib_ver[${i}]} | ${SEDCOMMAND} -e 's|.so$||g'`

    current_lib="${lib_file}.${VERSION}.dylib"
    files=`cd "${NX_LIB}" && ${LSCOMMAND} "${lib_file}."*"."*"."*".dylib" 2>&1`

    if [ $? = 0 ];
    then
      for j in ${files}
      do
        if [ -f "${NX_LIB}/${j}" ]  && [ "${j}" != "${current_lib}" ];
        then
          commandRm "${NX_LIB}/${j}" "cmd"
        fi
      done
    fi
  done
}

removeOldLibraries()
{
  if [ "x${system}" = "xsolaris" ];
  then
    return 0
  fi

  if [ "x${system}" = "xmacosx" ];
  then
    removeOldLibrariesMac

    return 0
  fi

  readlink_ok=0
  ${READLINKCOMMAND} --version > /dev/null 2>&1

  if [ $? = 0 ];
  then
    readlink_ok=1
  fi

  NX_LIB="${NX_ROOT}/lib"

  for ((i=0;i<${#tab_lib_ver[@]};i++));
  do
    if [ -h "${NX_LIB}/${tab_lib_ver[${i}]}" ];
    then
      if [ ${readlink_ok} -eq 1 ];
      then
        link_file=`${READLINKCOMMAND} "${NX_LIB}/${tab_lib_ver[${i}]}" 2>/dev/null`
      else
        link_file=`${LSCOMMAND} -l "${NX_LIB}/${tab_lib_ver[${i}]}" | ${AWKCOMMAND} '{print $11;}' 2>/dev/null`
      fi

      if [ "x${link_file}" != "x" ];
      then
        files=`${LSCOMMAND} "${NX_LIB}/${tab_lib_ver[${i}]}"*`

        for j in ${files}
        do
          if [ ! -h "${j}" ] && [ "${j}" != "${NX_LIB}/${link_file}" ];
          then
            commandRm "${j}" "cmd"
          fi
        done
      else
        printMsg "Error while reading value of symbolic link for file: ${NX_LIB}/${tab_lib_ver[${i}]}" "cmd"
      fi
    fi
  done
}

checkSkippingUninstall ()
{
  printMsgDebug "checkSkippingUninstall: ($1,$2)"
  ret_checkSkippingUninstall=0

  productName="${1}"
  packageName="${2}"

  if [ "x${productName}" = "xplayer" ];
  then
    getConfigFileName "server" "server"
    servercfg=${ret_getConfigFileName}
    if [ -f "${ret_getConfigFileName}" ];
    then
      productNameToCheck="server"
    else
      productNameToCheck="node"
    fi
  elif [ "x${productName}" = "xserver" ];
  then
    productNameToCheck="player"
  elif [ "x${productName}" = "xnode" ];
  then
    productNameToCheck="player"
  fi

#  getConfigFileName "connect" "${productNameToCheck}"
#  connectcfg=${ret_getConfigFileName}
  getConfigFileName "server" "${productNameToCheck}"
  servercfg=${ret_getConfigFileName}
  getConfigFileName "player" "${productNameToCheck}"
  playercfg=${ret_getConfigFileName}
  getConfigFileName "node" "${productNameToCheck}"
  nodecfg=${ret_getConfigFileName}

  if [ "x${packageName}" = "xclient" ];
  then
    if [ "x${productName}" = "xserver" ] || [ "x${productName}" = "xnode" ];
    then
      if [ -f "${playercfg}" ];
      then
        ret_checkSkippingUninstall=1
        return 0
      fi
    elif [ "x${productName}" = "xplayer" ];
    then
      if [ -f "${servercfg}" ] || [ -f "${nodecfg}" ];
      then
        ret_checkSkippingUninstall=1
        return 0
      fi
    fi
  elif [ "x${packageName}" = "xplayer" ];
  then
    #if [ "x${productName}" = "xserver" ] || [ "x${productName}" = "xnode" ];
    if [ "x${productName}" = "xserver" ];
    then
      if [ -f "${playercfg}" ];
      then
#        getValueFromCfgFile "StandalonePackage" "${playercfg}"
#        if [ "${ret_getValueFromCfgFile}" = "2" ] && [ ${cfg_val} = "yes" ];
#        then
          ret_checkSkippingUninstall=1
          return 0
#        fi
      fi
    elif [ "x${productName}" = "xplayer" ];
    then
      #if [ -f "${servercfg}" ] || [ -f "${nodecfg}" ];
      if [ -f "${servercfg}" ];
      then
        ret_checkSkippingUninstall=1
        return 0
      fi
    fi

  fi

  return 0
}

checkIsUpdateFromOldPreview ()
{
  #
  # Update from old preview is not supported
  #

  return 0

#  if [ "x${PACKAGE_NAME}" = "xnode" ];
#  then
#    if [ -f "${NX_ROOT}/bin/nxssh" ] || [ -f "${NX_ROOT}/bin/nxhtd" ];
#    then
#      commandRm "${NX_ROOT}/bin/nxssh"
#      commandBackupMvFile "${NX_ROOT}/etc/node.lic" "backup" "error"
#      commandBackupMvFile "${NX_ROOT}/etc/server.lic" "backup" "error"
#      commandCp "${NX_ROOT}/etc/node.lic.sample" "${NX_ROOT}/etc/node.lic" "error"
#      commandCp "${NX_ROOT}/etc/server.lic.sample" "${NX_ROOT}/etc/server.lic" "error"
#FIXME:
#      checkUserExist "nxhtd"
#      if [ "x${ret_checkUserExist}" = "x1" ];
#      then
#        removeNxhttpdUser "nxhtd"
#      fi
#      commandRmDirRecursively "/etc/NX/localhost"
#    else
#      printMsg "Checking if instalaltion on uninstalled Prev" "onlylog"
#      if [ ! -f "${NX_ROOT}/etc/node.cfg" ] && [ -f "${NX_ROOT}/etc/node.cfg.backup" ] && [ -f "${NX_ROOT}/etc/node.lic" ] && [ -f "${NX_ROOT}/etc/node.lic.sample" ];
#      then
#        commandBackupMvFile "${NX_ROOT}/etc/node.lic" "backup.old" "error"
#      fi
#      if [ ! -f "${NX_ROOT}/etc/server.cfg" ] && [ -f "${NX_ROOT}/etc/server.cfg.backup" ] && [ -f "${NX_ROOT}/etc/server.lic" ] && [ -f "${NX_ROOT}/etc/server.lic.sample" ];
#      then
#        commandBackupMvFile "${NX_ROOT}/etc/server.lic" "backup.old" "error"
#      fi
#    fi
#  fi
}

MAC_UNINSTALL_PLIST="com.nomachine.uninstall.plist"
MAC_UNINSTALL_SCRIPT="nxuninstall.sh"

uninstallMacUninstallAgent ()
{
  if [ "${system}" != "macosx" ];
  then
    return 0
  fi

  runCommand "${LAUNCHCTLCOMMAND} unload -w /Library/LaunchDaemons/${MAC_UNINSTALL_PLIST}" "Cannot unload uninstall plist file" "warn"
  commandRm "/Library/LaunchDaemons/${MAC_UNINSTALL_PLIST}" "cmd"

  commandRm "/Library/Application Support/NoMachine/${MAC_UNINSTALL_SCRIPT}" "cmd"
}

installMacUninstallAgent ()
{
  if [ "${system}" != "macosx" ];
  then
    return 0
  fi

  if [ ! -d "/Library/Application Support/NoMachine" ];
  then
    commandMkDir "/Library/Application Support/NoMachine"
  fi

  out=`${LAUNCHCTLCOMMAND} list | ${GREPCOMMAND} com.nomachine.uninstall 2>/dev/null`
  if [ "x${out}" != "x" ];
  then
    runCommand "${LAUNCHCTLCOMMAND} remove com.nomachine.uninstall" "Cannot remove uninstall plist file" "nolog"
  fi

  commandInstall "root" "${ROOTGNAME}" "0755" "${NX_ROOT}/share/mac/launchd/${MAC_UNINSTALL_SCRIPT}" "/Library/Application Support/NoMachine/${MAC_UNINSTALL_SCRIPT}" "cmd"

  commandCp "${NX_ROOT}/share/mac/launchd/${MAC_UNINSTALL_PLIST}" "/Library/LaunchDaemons/" "cmd"
  runCommand "${LAUNCHCTLCOMMAND} load -w /Library/LaunchDaemons/${MAC_UNINSTALL_PLIST}" "Cannot load uninstall plist file" "warn"
}

isPortBusy()
{
  port=$1
  hostname=$2

  ret_isPortBusy=0

  if [ "x${hostname}" = "x" ];
  then
    hostname="127.0.0.1"
  fi
  
  out=`(${ECHOCOMMAND} >/dev/tcp/$hostname/$port) &>/dev/null`
  if [ $? -eq 0 ]; then
    ret_isPortBusy=1
  fi
}

getNxdPort ()
{
  getValueFromCfgFile "NXPort" "${SERVER_USR_CONFIG_FILE}"

  if [ "${ret_getValueFromCfgFile}" = "2" ];
  then
    ret_getNxdPort="${cfg_val}"
  else
    ret_getNxdPort="${DEFAULT_NXD_PORT}"
  fi
}

getNxHtdPort ()
{
  ret_getNxHtdPort=""

  getHtdPortFromConfigFile
}


printServicePortStatus ()
{
  getNxdPort
  getNxHtdPort
 
  printMsgNoDot "NoMachine was configured to run the following services:"
  printMsgNoDot "NX service on port: ${ret_getNxdPort}"
  dialog_msg="NoMachine was configured to run the following service: <br> <br>NX service on port: ${ret_getNxdPort}"

  
  if [ "x${ret_getNxHtdPort}" != "x" ];
  then 
    services_count=1 
    if [ "x${ret_getNxHtdsPort}" != "x" ];
    then
      services_count=2 
    fi

    if [ ${services_count} -gt 1 ];
    then
      #printMsgNoDot "Additional services were configured to run:"
      dialog_msg="${dialog_msg} <br> <br>Additional services were configured to run:"
    else 
      #printMsgNoDot "An additional service was configured to run:"
      dialog_msg="${dialog_msg} <br> <br>An additional service was configured to run:"
    fi

    printMsgNoDot "HTTP service on port: ${ret_getNxHtdPort}"
    dialog_msg="${dialog_msg} <br> <br>HTTP service on port: ${ret_getNxHtdPort}"

    if [ "x${ret_getNxHtdsPort}" != "x" ];
    then
      printMsgNoDot "HTTPS service on port: ${ret_getNxHtdsPort}"
      dialog_msg="${dialog_msg} <br> HTTPS service on port: ${ret_getNxHtdsPort}"
    fi
  fi

}

printVGLInfo ()
{
  printMsgNoDot "NoMachine was configured to use HW accelerated OpenGL."
  printMsgNoDot "To activate it reboot the machine or restart X :0."
}

#####################################################################################
############################# SELinux Functions #####################################
#####################################################################################
getSELinuxMode()
{
# 0 - Disabled, 1 - Permissive, 2 - Enforcing
  printMsgDebug "getSELinuxMode: ()"
  ret_getSELinuxMode=0

  semode=`${GETENFORCECOMMAND} 2>/dev/null`

  if [ "x$semode" = "xEnforcing" ];
  then
    ret_getSELinuxMode=2
    return 0
  elif [ "x$semode" = "xPermissive" ];
  then
    ret_getSELinuxMode=1
    return 0
  elif [ "x$semode" = "xDisabled" ];
  then
    ret_getSELinuxMode=0
    return 0
  fi

#  if [ -e /selinux/enforce ];
#  then
#    semode=`${CATCOMMAND} /selinux/enforce`

#    ret_getSELinuxMode=`${EXPRCOMMAND} $semode + 1`
#    return 0
#  else
#    return 0
#  fi
}

isEnabledSELinux()
{
# 0 - Disabled, 1 - Enabled
  printMsgDebug "isEnabledSELinux: ()"
  ret_isEnabledSELinux=0

  getSELinuxMode
  if [ $ret_getSELinuxMode = 0 ];
  then
    return 0
  else
    ret_isEnabledSELinux=1
    return 0
  fi
}

setSELinuxStatus()
{
  if [ "x$SELINUX_ENABLED" = "x" ];
  then
    isEnabledSELinux
    SELINUX_ENABLED=$ret_isEnabledSELinux
  fi
}

setSELinuxStatus


setSELinuxExecStack()
{
  #out=`${EXECSTACKCOMMAND} --version 2>&1 > /dev/null`
  if [ ! -x "${EXECSTACKCOMMAND}" ];
  then
    printMsg "Skipping setting an executable stack flag for binaries. Command not found: ${EXECSTACKCOMMAND}" "cmd"
    return 0
  fi

  for ((i=0;i<${#selinux_execstack_files[@]};i++)); do
    if [ -f "${NX_ROOT}/${selinux_execstack_files[${i}]}" ];
    then
      runCommand "${EXECSTACKCOMMAND} -s '${NX_ROOT}/${selinux_execstack_files[${i}]}'" "Cannot set executable stack flag for: ${NX_ROOT}/${selinux_execstack_files[${i}]}" "cmd"
    fi
  done
}

#####################################################################################
getLastServerPackage ()
{
  LAST_SUBPACKAGE_SERVER="server"
}

procedureFinalUninstallNode ()
{
  if [ "${system}" = "macosx" ];
  then
    commandRmFiles "/var/db/receipts/com.nomachine.NoMachineNode"
    commandRmDirRecursively "${NX_ROOT}/lib"

    # for old versions (<=10.5)
    commandRmDirRecursively "/Library/Receipts/nxclient-${VERSION}-nc.pkg"
    commandRmDirRecursively "/Library/Receipts/nxnode-${VERSION}-n.pkg"
  fi
}

initializeOperation ()
{
  operation=$1

  umask 022
  LOGFILE="$UNINSTALLOG"
  PROCESS="$UNINSTALL"

  if [ ${PACKAGE_NAME} = "node" ] || [ ${PACKAGE_NAME} = "server" ];
  then
    if [ $operation = "update" ];
    then
      if [ ! -f "$CONFIG_FILE" ];
      then
        printMsgNoDot "Initialization failed. Cannot open file: ${CONFIG_FILE}" "error"
        printMsgNoDot "No such file or directory. Please try to fix the problem by" "error"
        printMsgNoDot "running: '${NX_ROOT}/scripts/setup/nx${PACKAGE_NAME} --install'." "error"
        exit 1
      fi
    fi
  fi

  case $operation in
    "install")       LOGFILE="$INSTALLOG"
                     PROCESS="$INSTALL"
                     ;;
    "install-basic") LOGFILE="$INSTALLOG"
                     PROCESS="$INSTALL"
                     ;;
    "uninstall")     LOGFILE="$UNINSTALLOG"
                     PROCESS="$UNINSTALL"
                     ;;
    "preuninstall")  LOGFILE="$UNINSTALLOG"
                     PROCESS="$UNINSTALL"
                     ;;
    "update")        LOGFILE="$UPDATELOG"
                     PROCESS="$UPDATE"
                     ;;
  esac

  createLogdirectory
  startLog

  upgrade=0

  if [ "${operation}" = "install-basic" ];
  then
    return 0
  fi

  if [ "${operation}" = "update" ];
  then
    getCfgFileVersion "${PACKAGE_NAME}" "${NX_ROOT}"

    if [ ${ret_getCfgFileVersion} = 0 ];
    then
      if [ "x${cfg_version}" != "x" ] && [ "${cfg_version}" != "4.0" ];
      then
        upgrade=1
      else
        checkIsUpdateFromOldPreview
      fi
    fi
  fi

  if [ "${operation}" = "install" ] || [ "${operation}" = "update" ];
  then
    if [ ! -f "${CONFIG_FILE}" ] && [ -f "${CONFIG_FILE}.backup" ] || [ -f "${LICENSE_FILE}" ];
    then
      getCfgFileVersion "${PACKAGE_NAME}" "${NX_ROOT}" ".backup"

      if [ ${ret_getCfgFileVersion} = 0 ];
      then
        if [ "x${cfg_version}" != "x" ] && [ "${cfg_version}" != "4.0" ];
        then

          #
          # Upgarde from unintatlled 3.X.
          #

          commandBackupMvFile "${LICENSE_FILE}" "backup" "error"
          commandMv "${CONFIG_FILE}.backup" "${CONFIG_FILE}.backup.old"
        fi
      fi
    fi
  fi
}

printOperationInfo ()
{
  printMsgDebug "getBasePackagePath: ($1,$2)"

  operation=$1
  upgrade=$2

  auxOp1=""
  auxOp2=""
  printSystemName=0

  if [ "$operation" = "update" ] && [ "$upgrade" = "1" ];
  then
    operation="upgrade"
  fi

  case $operation in
    "install")       auxOp1="Installing"
                     auxOp2="Install"
                     auxOp3="install"
                     printSystemName=1
                     ;;
    "install-basic") auxOp1="Installing"
                     auxOp2="Install"
                     auxOp3="install"
                     printSystemName=1
                     ;;
    "uninstall")     auxOp1="Uninstalling"
                     auxOp2="Uninstall"
                     auxOp3="uninstall"
                     ;;
    "preuninstall")  auxOp1="Pre-uninstalling"
                     auxOp2="Pre-uninstall"
                     auxOp3="pre-uninstall"
                     ;;
    "update")        auxOp1="Updating"
                     auxOp2="Update"
                     auxOp3="update"
                     printSystemName=1
                     ;;
    "upgrade")       auxOp1="Upgrading"
                     auxOp2="Upgrade"
                     auxOp3="upgrade"
                     printSystemName=1
                     ;;
  esac

  printDate=0
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    if [ "x${operation}" != "xpreuninstall" ];
    then
      printDate=1
    fi
  else
    if [ "x${NX_MPKG_PACKAGE}" = "xserver" ];
    then
      if [ "x$operation" = "xinstall" ] || [ "x$operation" = "xupdate" ] || [ "x$operation" = "xupgrade" ];
      then
        if [ "x${PACKAGE_NAME}" = "xclient" ];
        then
          printDate=1
        fi
      fi

      if [ "x$operation" = "xinstall-basic" ];
      then
        if [ "x${PACKAGE_NAME}" = "xnode" ];
        then
          printDate=1
        fi
      fi

      getLastServerPackage
      if [ "x$operation" = "xuninstall" ] && [ "x${PACKAGE_NAME}" = "x${LAST_SUBPACKAGE_SERVER}" ];
      then
        printDate=1
      fi
    fi

    if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
    then
      if [ "x$operation" = "xinstall" ] || [ "x$operation" = "xupdate" ] || [ "x$operation" = "xupgrade" ];
      then
        if [ "x${PACKAGE_NAME}" = "xclient" ];
        then
          printDate=1
        fi
      fi

      if [ "x$operation" = "xuninstall" ] && [ "x${PACKAGE_NAME}" = "xnode" ];
      then
        printDate=1
      fi
    fi

    if [ "x${PACKAGE_NAME}" = "xnode" ];
    then
      if [ "x$operation" = "xinstall" ];
      then
        isInstalledProduct "player"
        if [ $ret_isInstalledProduct = 1 ];
        then
          printDate=1
        fi
      fi
    fi

    if [ "x${NX_MPKG_PACKAGE}" = "xplayer" ];
    then
      if [ "x$operation" = "xinstall" ] || [ "x$operation" = "xupdate" ] || [ "x$operation" = "xupgrade" ];
      then
        if [ "x${PACKAGE_NAME}" = "xclient" ];
        then
          printDate=1
        fi

        if [ "x${PACKAGE_NAME}" = "xplayer" ] && [ "x$operation" = "xinstall" ];
        then
          isInstalledProduct "server"
          if [ $ret_isInstalledProduct = 1 ];
          then
            printDate=1
          else
            isInstalledProduct "connect"
            if [ $ret_isInstalledProduct = 1 ];
            then
              printDate=1
            fi
          fi
        fi
      fi

      if [ "x$operation" = "xuninstall" ] && [ "x${PACKAGE_NAME}" = "xplayer" ];
      then
        printDate=1
      fi
    fi

  fi

  if [ "x$printDate" = "x1" ];
  then
    currentTime=`${DATECOMMAND} +'%a %b %d %T %Y'`
    printMsg "Starting $auxOp3 at: $currentTime"

    if [ "x${PACKAGE_NAME}" = "x${LAST_SUBPACKAGE_SERVER}" ];
    then
      if [ "x$operation" = "xuninstall" ];
      then
        shutdownServer
        stopNXServer
      fi
    fi
  fi

  printMsg "${auxOp1}: nx${PACKAGE_NAME} version: ${VERSION}"

  if [ "$printSystemName" = "1" ];
  then
    detectedSystem=$system
    if [ "$system" = "macosx" ];
    then
      detectedSystem="Mac OS X"
    elif [ "$system" = "solaris" ];
    then
      detectedSystem="Solaris"
    elif [ "$system" = "redhat" ];
    then
      detectedSystem="Red Hat"
    elif [ "$system" = "fedora" ];
    then
      detectedSystem="Fedora"
    elif [ "$system" = "debian" ];
    then
      if [ "x${issue}" = "xubuntu" ];
      then
        detectedSystem="Ubuntu"
      elif [ "x${issue}" = "xlinuxmint" ];
      then
        detectedSystem="LinuxMint"
      else
        detectedSystem="Debian"
      fi
    elif [ "$system" = "suse" ];
    then
      detectedSystem="SUSE"
    elif [ "$system" = "slackware" ];
    then
      detectedSystem="Slackware"
    elif [ "$system" = "mandriva" ];
    then
      detectedSystem="Mandriva"
    fi

    if [ "x${SYSTEM}" = "x" ];
    then
      printMsg "Using installation profile: $detectedSystem"
    else
      printMsg "Using installation profile: $detectedSystem"
    fi
  fi

  if [ "x$operation" = "xuninstall" ];
  then
    killNXApplications
  fi

  printMsg "$auxOp2 log is: $LOGFILE"
}

addRPMrequiredFiles ()
{
  #This is a workaround for warnings on system with rpm package manager

  if [[ "x${system}" = "xmandriva" ]] || [[ "x${system}" = "xfedora" ]] || [[ "x${system}" = "xredhat" ]] || [[ "x${system}" = "xsuse" ]]; then
    if [[ "x${operation}" = "xuninstall" ]]; then
      rpmVersion=`rpm --version`
      rpmVersionFirst=`${ECHOCOMMAND} ${rpmVersion} | ${CUTCOMMAND} -d " " -f 3 | ${CUTCOMMAND} -d "." -f 1`
      rpmVersionSecond=`${ECHOCOMMAND} ${rpmVersion} | ${CUTCOMMAND} -d " " -f 3 | ${CUTCOMMAND} -d "." -f 2`

      if [ $rpmVersionFirst -eq 4 ]; then
        if [ $rpmVersionSecond -eq 11 ] || [ $rpmVersionSecond -gt 11 ]; then 
          ${MKDIRCOMMAND} -p /etc/NX/
          ${MKDIRCOMMAND} -p /etc/NX/${NX_MPKG_PACKAGE}/
          ${MKDIRCOMMAND} -p /etc/NX/${NX_MPKG_PACKAGE}/localhost
          ${MKDIRCOMMAND} -p /etc/NX/${NX_MPKG_PACKAGE}/packages
          ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/packages/nxplayer.tar.gz
          ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/packages/nxclient.tar.gz

	  if [[ "x${NX_MPKG_PACKAGE}" = "xplayer" ]]; then
            ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/localhost/player.cfg.sample
	  fi

          if [[ "x${NX_MPKG_PACKAGE}" = "xserver" ]]; then 
            ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/localhost/server.cfg.sample
            ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/packages/nxserver.tar.gz
            ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/packages/nxnode.tar.gz

	    if [[ -f "${NX_ROOT}/etc/cloud.cfg.backup" ]]; then
              ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/packages/nxwebplayer.tar.gz
            fi
          fi

          if [[ "x${NX_MPKG_PACKAGE}" = "xnode" ]]; then
            ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/packages/nxnode.tar.gz
            ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/packages/nxserver.tar.gz
            ${TOUCHCOMMAND} /etc/NX/${NX_MPKG_PACKAGE}/localhost/node.cfg.sample
            ${TOUCHCOMMAND} /etc/NX/nxnode
	  fi
	fi
      fi
    fi
  fi
}

printSummaryInfo ()
{
  printMsgDebug "printSummaryInfo: ($1,$2)"

  operation=$1
  upgrade=$2
  auxProcess=""

  if [ "x${operation}" = "xupdate" ] && [ "x${upgrade}" = "x1" ];
  then
    operation="upgrade"
  fi

  operation2=$operation
  case $operation in
    "install")       auxProcess="Install"
                     ;;
    "install-basic") auxProcess="Install"
                     operation2="install"
                     ;;
    "uninstall")     auxProcess="Uninstall"
                     ;;
    "preuninstall")  auxProcess="Pre-uninstall"
                     ;;
    "update")        auxProcess="Update"
                     ;;
    "upgrade")       auxProcess="Upgrade"
                     ;;
  esac

if [ "x${NX_SKIP_UNINSTALL}" != "x1" ];
then

  if [ -f "${NX_ROOT}/share/documents/${PACKAGE_NAME}/${operation}-notices" ];
  then
    if [ "x${SHOWUPDATEINFO}" = "xyes" ];
    then
      printMsgNoDot "Displaying file: ${NX_ROOT}/share/documents/${PACKAGE_NAME}/${operation}-notices"
      ${CATCOMMAND} "${NX_ROOT}/share/documents/${PACKAGE_NAME}/${operation}-notices"
    fi
  fi

  if [ "${SHOWCUPSINFO}" = "yes" ];
  then
    SHOWWARNINFO="yes"
    if [ -f "${NX_ROOT}/share/documents/${PACKAGE_NAME}/cups-info" ];
    then
      printMsgNoDot "Displaying file: ${NX_ROOT}/share/documents/${PACKAGE_NAME}/cups-info"
      ${CATCOMMAND} "${NX_ROOT}/share/documents/${PACKAGE_NAME}/cups-info"
    fi
  fi

  if [ "x${SHOWPULSEINFO}" = "xyes" ];
  then
    #lack of PulseaAudio is not an error
    SHOWWARNINFO="no"
    if [ -f "${NX_ROOT}/share/documents/${PACKAGE_NAME}/pulseaudio-info" ];
    then
      printMsgNoDot "Displaying file: ${NX_ROOT}/share/documents/${PACKAGE_NAME}/pulseaudio-info"
      ${CATCOMMAND} "${NX_ROOT}/share/documents/${PACKAGE_NAME}/pulseaudio-info"
    fi
  fi

  if [ "x${SHOWOSSINFO}" = "xyes" ];
  then
    if [ -f "${NX_ROOT}/share/documents/${PACKAGE_NAME}/oss-info" ];
    then
      printMsgNoDot "Displaying file: ${NX_ROOT}/share/documents/${PACKAGE_NAME}/oss-info"
      ${CATCOMMAND} "${NX_ROOT}/share/documents/${PACKAGE_NAME}/oss-info"
    fi
  fi

  if [ "${PACKAGE_NAME}" = "server" ];
  then
    procedureprintbrandmessages
  fi

  if [ "${operation}" = "uninstall" ];
  then
    if [ "x${NX_SKIP_UNINSTALL}" != "x1" ] && [ "x${NX_CHANGE_MODE}" != "x1" ];
    then
      cleanPackageFiles
    fi
  fi

  if [ "${SHOWWARNINFO}" = "yes" ];
  then
    capitalizeFirst ${PACKAGE_NAME}
    printMsg "${retCapitalizeFirst} ${operation2} completed with warnings"
    printMsg "Please review the ${operation2} log for details"
  fi
fi

  printDate=0
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    if [ "x${operation}" != "xpreuninstall" ];
    then
      printDate=1
    fi
  else

    if [ "x${NX_MPKG_PACKAGE}" = "xserver" ];
    then
      getLastServerPackage

      if [ "x${operation}" = "xinstall" ] || [ "x${operation}" = "xupdate" ] || [ "x${operation}" = "xupgrade" ];
      then
        if [ "x${PACKAGE_NAME}" = "x${LAST_SUBPACKAGE_SERVER}" ];
        then
          printDate=1

          if [ "x${operation}" = "xinstall" ];
          then
            installMacUninstallAgent
          else

            if [ "x${NX_CHANGE_MODE}" != "x1" ];
            then
              uninstallMacUninstallAgent
            fi

            installMacUninstallAgent
          fi
        fi
      elif [ "x${operation}" = "xinstall-basic" ] && [ "x${PACKAGE_NAME}" = "x${NX_MPKG_PACKAGE}" ];
      then
          printDate=1
      fi

      if [ "x${operation}" = "xuninstall" ] && [ "x${PACKAGE_NAME}" = "xclient" ];
      then
        printDate=1
        uninstallMacUninstallAgent
      fi
    fi

    if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
    then
      if [ "x${operation}" = "xinstall" ] || [ "x${operation}" = "xupdate" ] || [ "x${operation}" = "xupgrade" ];
      then
        if [ "x${PACKAGE_NAME}" = "xnode" ];
        then
          printDate=1

          if [ "x${operation}" = "xinstall" ];
          then
            installMacUninstallAgent
          else
            uninstallMacUninstallAgent
            installMacUninstallAgent
          fi

        fi
      fi

      if [ "x${operation}" = "xuninstall" ] && [ "x${PACKAGE_NAME}" = "xclient" ];
      then
        printDate=1
        uninstallMacUninstallAgent
      fi
    fi

    if [ "x${NX_MPKG_PACKAGE}" = "xwebplayer" ];
    then
      if [ "x${operation}" = "xinstall" ] || [ "x${operation}" = "xupdate" ] || [ "x${operation}" = "xupgrade" ];
      then
        if [ "x${PACKAGE_NAME}" = "xwebplayer" ];
        then
          printDate=1
        fi
      fi

      if [ "x${operation}" = "xuninstall" ];
      then
        printDate=1
      fi
    fi

    if [ "x${NX_MPKG_PACKAGE}" = "xplayer" ];
    then
      if [ "x${operation}" = "xinstall" ] || [ "x${operation}" = "xupdate" ] || [ "x${operation}" = "xupgrade" ];
      then
        if [ "x${PACKAGE_NAME}" = "xplayer" ];
        then
          printDate=1

          if [ "x${system}" != "xmacosx" ];
          then
            startNXServerByOtherProduct
          fi

          if [ "x${system}" = "xmacosx" ];
          then
            if [ "x${operation}" = "xinstall" ];
            then
              installMacUninstallAgent
            else
              uninstallMacUninstallAgent
              installMacUninstallAgent
            fi

          fi
        fi
      fi

      if [ "x${operation}" = "xuninstall" ] && [ "x${PACKAGE_NAME}" = "xclient" ];
      then
        printDate=1
        uninstallMacUninstallAgent
      fi
    fi

  fi

  if [ "x${printDate}" = "x1" ];
  then

    if [ "x${NX_INSTALLATION_ACTION}" != "x" ];
    then
      auxProcess="${NX_INSTALLATION_ACTION}"
    fi

    if [ "x${operation}" = "xuninstall" ];
    then
      finalRemoveLeftoversPkg
      removeVARDir
    fi

    currentTime=`${DATECOMMAND} +'%a %b %d %T %Y'`

    getInstallationStatus
    if [ "x${ret_getInstallationStatus}" = "x1" ];
    then
      printMsg "${auxProcess} completed with errors at: ${currentTime}"
    elif [ "x${ret_getInstallationStatus}" = "x2" ];
    then
      #printMsg "${auxProcess} completed with warnings at: ${currentTime}"
      printMsg "${auxProcess} completed at: ${currentTime}"
      addRPMrequiredFiles
    else
      printMsg "${auxProcess} completed at: ${currentTime}"
      addRPMrequiredFiles
    fi

    if [ "x${operation}" = "xinstall" ] || [ "x${operation}" = "xupdate" ];
    then

      if [ "x${NX_MPKG_PACKAGE}" = "xnode" ] || [ "x${NX_MPKG_PACKAGE}" = "xserver" ];
      then
        printServicePortStatus
      fi

      if [ -f "${NX_ROOT}/.vgl_reboot" ];
      then
        commandRm "${NX_ROOT}/.vgl_reboot"
        printVGLInfo
      fi

      if [ "x${operation}" = "xupdate" ];
      then
         ${ECHOCOMMAND} "Updated to ${VERSION} at: ${currentTime}" >> "${NX_VAR_DIR}/log/nxerror.log"
      fi

    fi
  fi

}


printusage ()
{

  if [ "x${PACKAGE_NAME}" = "xconnect" ];
  then
    printusageConnect
    return
  fi

  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "Usage: `${BASENAMECOMMAND} $0` ACTION"
  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "Actions:"
  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "--install        {SYSTEM}   Run the NoMachine ${PACKAGE_NAME} install procedure for the"
  ${ECHOCOMMAND} "                            specified system or distribuition"
  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "--update         {SYSTEM}   Run the NoMachine ${PACKAGE_NAME} update procedure for the"
  ${ECHOCOMMAND} "                            specified system or distribution"

  if [ "x${PACKAGE_NAME}" = "xnode" ];
  then
    ${ECHOCOMMAND}
    ${ECHOCOMMAND} "--availablesessionsetup     Update forcibly list of available session types"
    ${ECHOCOMMAND} "                            in the configuration files. This will override"
    ${ECHOCOMMAND} "                            custom configurations."
  fi

  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "--uninstall                 Run the NoMachine server uninstall procedure."
  ${ECHOCOMMAND}

  if [ ${PACKAGE_NAME} = "server" ];
  then
    ${ECHOCOMMAND} "--pre-uninstall             Disable access to new NX sessions, terminate"
    ${ECHOCOMMAND} "                            sessions and reset the session DBs."
    ${ECHOCOMMAND}
    ${ECHOCOMMAND} "--keygen                    Generate a new pair of SSH keys for the NoMachine"
    ${ECHOCOMMAND} "                            login. After running this procedure, clients will"
    ${ECHOCOMMAND} "                            use the key: /usr/NX/share/keys/default.id_dsa.key"
    ${ECHOCOMMAND} "                            to connect to this NX server."
    ${ECHOCOMMAND}
    ${ECHOCOMMAND} "--keyrestore                Restore the SSH key provided with the server"
    ${ECHOCOMMAND} "                            package. Current key will be moved to"
    ${ECHOCOMMAND} "                            default.id_dsa.key.backup file."
    ${ECHOCOMMAND}
  fi

  ${ECHOCOMMAND} "--help                      Show this message"
  ${ECHOCOMMAND}

  printHelpSystemInfo

  ${ECHOCOMMAND} "$errMsg"

  exit $E_WRONGARGS
}

printusageConnect ()
{

  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "Usage: `${BASENAMECOMMAND} $0` ACTION"
  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "Actions:"
  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "--uninstall                 Run the NoMachine ${PACKAGE_NAME} uninstall procedure for the"
  ${ECHOCOMMAND} "                            specified system or distribution."
  ${ECHOCOMMAND}
  ${ECHOCOMMAND} "--help                      Show this message"
  ${ECHOCOMMAND}

  ${ECHOCOMMAND} "$errMsg"

  exit $E_WRONGARGS
}

printMsgStartOperation ()
{
  printMsg "Starting: $1 operation at: $currentTime"
}

getScriptParametersConnect ()
{
  action="$1"

  error=0
  case "$action" in
      "--uninstall"      ) error=0;;
      "--usage"          ) error=0 && action="--help";;
      "--help"           ) error=0;;
      ""                 ) printMsg "Please specify an action" "nolog" && error=1 ;;
      *                  ) printMsg "ERROR: Unknown action '$action'" "nolog" && error=1 ;;
    esac

  if [ "x$error" = "x1" ];
  then
    printusageConnect
    exit 1
  fi
}

getScriptParameters ()
{
  action="$1"
  par2="$2"
  par3="$3"

  ARGS=1
  E_WRONGARGS=65

  action_ok=0
  if [ "${PACKAGE_NAME}" = "node" ];
  then
    case "$action" in
      "--printingsetup"          )  printingsetupParm="$par2"
                                    return;;
      "--audiosetup"             )  audiosetupParm="$par2"
                                    return;;
      "--sharingsetup"           )  sharingsetupParm="$par2"
                                    return;;
      "--vmwaresetup"            )  vmwaresetupParm="$par2"
                                    return;;
      "--osquery"                )  osquery_par="$par2"
                                    return;;
      "--availablesessionsetup"  )  return;;

    esac
  elif [ "${PACKAGE_NAME}" = "server" ];
  then
    case "$action" in
      "--postupgrade"   ) needSystem=0
                          action_ok=1;;
      "--preuninstall"  ) needSystem=0
                          action_ok=1;;
      "--pre-uninstall" ) needSystem=0
                          action_ok=1;;
      "--server-keygen" ) needSystem=0
                          action_ok=1;;
      "--keygen"        ) needSystem=0
                          action_ok=1;;
      "--keyrestore"    ) needSystem=0
                          action_ok=1;;
      "--nxkeygen"      ) needSystem=0
                          action_ok=1;;
      "--osquery"       ) osquery_par="$par2"
                          return;;
      "--startnxhtd"    ) action_ok=1
                          return;;
      "--mode"          ) action_ok=1
                          install_mode=$par2
                          return;;
      "--enableservices") needSystem=0
                          service="$par2"
                          action_ok=1
                          return;;
      "--disableservices") needSystem=0
                          service="$par2"
                          action_ok=1
                          return;;
      "--checkservices")  needSystem=0
                          action_ok=1
                          return;;
      "--install-pam"   ) needSystem=0
                          action_ok=1
                          return;;
      "--checkpam"    )   action_ok=1
                          return;;
      "--pathsetup"   )   action_ok=1
                          return;;
    esac
  fi

  if [ "$action_ok" = "0" ];
  then
    case "$action" in
      "--install"            ) needSystem=1;;
      "--update"             ) needSystem=1;;
      "--uninstall"          ) needSystem=0;;
      "--usage"              ) needSystem=0;;
      "--help"               ) needSystem=0;;
      "--install-service"    ) needSystem=1;;
      "--uninstall-service"  ) needSystem=1;;
      ""                     ) ARGS=-1 && printMsg "Please specify an action" "nolog" && needSystem=0 ;;
      *                      ) ARGS=-1 && printMsg "ERROR: Unknown action '$action'" "nolog" && needSystem=0 ;;
    esac
  fi

  if [ -n "$par2" ];
  then
    ARGS=`${EXPRCOMMAND} $ARGS + 1`

    if [ "$action" = "--printingsetup" ];
    then
      action_par="$par2"
    elif [ "$action" = "--install-service" ] || [ "$action" = "--uninstall-service" ];
    then
      action_service="$par2"
    else
      case "$par2" in
        "--personal" ) action_par=$par2 && needSystem=0;;
        "--basic"    ) action_par=$par2 && needSystem=0;;
        "--silent"   ) NX_INSTALL_SILENT=1 && needSystem=0;;
		"--auto"     ) action_par=$par2 && needSystem=0;;
        ""           ) ARGS=-1 && needSystem=0;;
        *            ) system=$par2 && SYSTEM=$par2 && needSystem=1;;
      esac
    fi
  fi

  if [ -n "$par3" ];
  then
    ARGS=`${EXPRCOMMAND} $ARGS + 1`
    system=$par3 && needSystem=1;
    SYSTEM=$system
  fi

  if [ "$needSystem" -eq 1 ];
  then
    case "$system" in
      "redhat"             ) ;;
      "suse"               ) ;;
      "slackware"          ) ;;
      "mandriva"           ) ;;
      "fedora"             ) ;;
      "debian"             ) ;;
      "solaris"            ) ;;
      "macosx"             ) ;;
      ""                   ) ARGS=-1 && errMsg="$PREFIX $ERROR ERROR: Unable to autodetect the operating system type, please specify it" ;;
      *                    ) ARGS=-1 && errMsg="$PREFIX $ERROR ERROR: Unsupported operating system '$system'" ;;
    esac
  fi

  if [ "$parCount" -ne "$ARGS" ]; # Check for proper no. of command line args.
  then
    printusage
  fi

  if [ "$action" = "--usage" ] || [ "$action" = "--help" ];
  then
    E_WRONGARGS=0
    printusage
  fi

  if [ ${PACKAGE_NAME} = "server" ];
  then

    NXSSH_RCODE=0

    if [ "$system" = "solaris" ];
    then
      FILE_AUTHORIZED_KEYS="$NXHOME/.ssh/authorized_keys"
      NXSSH_RCODE=255
      if [ -f /etc/.login ];
      then
        rcCsh="/etc/.login"
      fi
    fi
  fi
}

if [ "x${PACKAGE_NAME}" = "xconnect" ];
then
  getScriptParametersConnect "$1"
else
  getScriptParameters "$1" "$2" "$3"
fi

runActionOsquery ()
{
  if [ "x$osquery_par" = "x" ];
  then
    LOGFILE="$UPDATELOG"
    createLogdirectory
    startLog
  fi

  getFullDistroName

  if [ "x$osquery_par" = "x1" ];
  then
    ${ECHOCOMMAND} "$VERSION"
  else
    ${ECHOCOMMAND} "NX> 731 Operating System: $VERSION"
  fi
}

runAction ()
{
  if [ "x${PACKAGE_NAME}" = "xconnect" ];
  then
    runActionConnect
    return
  fi

  if [ "$action" = "--install" ];
  then
    if [ "$action_par" = "--personal" ];
    then
      installPersonal
    elif [ "$action_par" = "--basic" ];
    then
      NX_INSTALL_BASIC=1

      procedureInstallBasic
    else
      procedureInstall
    fi
  fi

  if [ "$action" = "--uninstall" ];
  then
    if [ "$action_par" = "--personal" ];
    then
      uninstallPersonal
    else
      procedureUninstall
    fi
  fi

  if [ "$action" = "--update" ];
  then
    if [ "$action_par" = "--personal" ];
    then
      updatePersonal
    elif [ "$action_par" = "--auto" ];
    then
      procedureUpdate "auto"
    else
      procedureUpdate
    fi
  fi

  if [ "$action" = "--install-service" ];
  then
    runActionInstallService "${action_service}"
  fi

  if [ "$action" = "--uninstall-service" ];
  then
    runActionUninstallService "${action_service}"
  fi

  runActionPackage
  return 0
}

########################################################################################
############################### DISTRO NAME ############################################

OS=`${UNAMECOMMAND} -s`
REV=`${UNAMECOMMAND} -r`
MACH=`${UNAMECOMMAND} -m`

tab_known_distro=(
/etc/annvix-release
/etc/arch-release
/etc/arklinux-release
/etc/aurox-release
/etc/blackcat-release
/etc/cobalt-release
/etc/conectiva-release
/etc/debian_version
/etc/debian_release
/etc/fedora-release
/etc/gentoo-release
/etc/immunix-release
knoppix_version
/etc/lfs-release
/etc/linuxppc-release
/etc/mandrake-release
/etc/mandriva-release
/etc/mandakelinux-release
/etc/mklinux-release
/etc/nld-release
/etc/pld-release
/etc/redhat-release
/etc/redhat_version
/etc/slackware-version
/etc/slackware-release
/etc/e-smith-release
/etc/release
/etc/sun-release
/etc/SuSE-release
/etc/novell-release
/etc/sles-release
/etc/tinysofa-release
/etc/turbolinux-release
/etc/lsb-release
/etc/ultrapenguin-release
#/etc/UnitedLinux-release
/etc/va-release
/etc/yellowdog-release
/etc/system-release
)

getVersionFromLSB()
{
  VERSION=""

  out_lsb=`PATH="/bin:/usr/bin:${PATH}" ${LSBRELEASECOMMAND} -d 2>/dev/null`

  if [ "x$out_lsb" = "x" ];
  then
    ret_getVersionFromLSB=1
    return 1
  fi

  VERSION=`${ECHOCOMMAND} $out_lsb | ${SEDCOMMAND} s/.*:\ //`
  printMsg "LSB System Version: $VERSION" "onlylog"

  ret_getVersionFromLSB=0
  return 0
}


getVersionFromFile()
{
  VERSION=`${HEADCOMMAND} -n 1 $1`
  printMsg "System Version (from release file): $VERSION" "onlylog"

  if [ "$1" != "/etc/debian_version" ];
  then
    printMsg "System Version (from release file): $VERSION" "onlylog"
  else
    grep_out=`${ECHOCOMMAND} $VERSION | ${GREPCOMMAND} [dD]ebian`
    if [ "x${grep_out}" = "x" ];
    then
      printMsg "System Version (from release file): Debian $VERSION" "onlylog"
      VERSION="Debian $VERSION"
    else
      printMsg "System Version (from release file): $VERSION" "onlylog"
    fi
  fi

  return 0
}


getVersionFromReleaseFile()
{
  printMsgDebug "getVersionFromReleaseFile: ()"
  ret_getVersionFromReleaseFile=0

  VERSION=""

  for ((i=0;i<${#tab_known_distro[@]};i++)); do
    if [ -f "${tab_known_distro[${i}]}" ];
    then
      getVersionFromFile "${tab_known_distro[${i}]}"
      return 0
    fi
  done

  ret_getVersionFromReleaseFile=1
  return 0
}

getDistroVersion ()
{
  ret_DistroVersion=""

  if [ -r "/etc/os-release" ];
  then
    ret_DistroVersion=$("${GREPCOMMAND}" "VERSION" "/etc/os-release" | \
                        "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | \
                        "${SEDCOMMAND}" -nre \
                         's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')
  elif [ -r "/etc/lsb-release" ] && [ "x${system}" != "xredhat" ];
  then
    ret_DistroVersion=$("${GREPCOMMAND}" "VERSION" "/etc/lsb-release" | \
                        "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | \
                        "${SEDCOMMAND}" -nre \
                         's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')
  elif [ -r "${DISTRO_FILE}" ] && [ "x${issue}" != "xubuntu" ] && \
       [ "x${issue}" != "xlinuxmint" ] ;
  then
    ret_DistroVersion=$("${CATCOMMAND}" "${DISTRO_FILE}" | "${SEDCOMMAND}" -nre \
                        's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')
  fi
}

getUbuntuVersion ()
{
  ret_ubuntuVersion=""

  if [ -r "/etc/os-release" ];
  then

    ret_ubuntuVersion=$("${GREPCOMMAND}" "VERSION" "/etc/os-release" | "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | "${SEDCOMMAND}" -nre 's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')

  elif [ -r "/etc/lsb-release" ];
  then

    ret_ubuntuVersion=$("${GREPCOMMAND}" "DISTRIB_RELEASE" "/etc/lsb-release" | "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | "${SEDCOMMAND}" -nre 's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')

  fi
}


getSuSEVersion ()
{
  ret_suseVersion=""

  if [ -r "/etc/os-release" ];
  then

    ret_suseVersion=$("${GREPCOMMAND}" "VERSION_ID" "/etc/os-release" | "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '"' -f 2 | "${TRCOMMAND}" -d ' ')

  elif [ -r "/etc/SuSE-release" ];
  then

    ret_suseVersion=$("${GREPCOMMAND}" "VERSION" "/etc/SuSE-release" | "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | "${SEDCOMMAND}" -nre 's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')

  fi
}

checkSLES ()
{
  ret_checkSLES="0"

  if [ "x${system}" != "xsuse" ];
  then
    return 0;
  fi

  if [ -r "/etc/os-release" ];
  then

    find_enterprise=$("${GREPCOMMAND}" "Enterprise" "/etc/os-release"  2>/dev/null )

  elif [ -r "/etc/SuSE-release" ];
  then

    find_enterprise=$("${GREPCOMMAND}" "Enterprise" "/etc/SuSE-release"  2>/dev/null )

  fi

  if [ "x${find_enterprise}" != "x" ];
  then
    ret_checkSLES="1"
  fi
}

getFullDistroName()
{
  printMsgDebug "getFullDistroName: ()"
  ret_getFullDistroName=1

  OS=`${UNAMECOMMAND} -s`

  VERSION="Unknown"

  if [ "${OS}" = "Darwin" ];
  then
    ver=`${SWVERSCOMMAND} | ${GREPCOMMAND} 'ProductVersion:' | ${GREPCOMMAND} -o '[0-9]*\.[0-9]*\.[0-9]*'`
    VERSION="Mac OS X $ver"
    return 0
  fi

  getVersionFromLSB
  if [ $ret_getVersionFromLSB = 0 ] && [ "x$VERSION" != "x" ];
  then
    ret_getFullDistroName=0
  fi

  if [ $ret_getFullDistroName != 0 ];
  then
    if [ "${OS}" = "SunOS" ];
    then
      getVersionFromReleaseFile
      ret_getFullDistroName=$ret_getVersionFromReleaseFile
      VERSION=`${ECHOCOMMAND} $VERSION | ${CUTCOMMAND} -d ' ' -f1-2`
    elif [ "${OS}" = "AIX" ];
    then
      VERSION="${OS} `oslevel` (`oslevel -r`)"
      ret_getFullDistroName=0
    elif [ "${OS}" = "Linux" ];
    then
      getVersionFromReleaseFile
      ret_getFullDistroName=$ret_getVersionFromReleaseFile

      if [ $ret_getFullDistroName = 1 ];
      then
        if [ -f /etc/UnitedLinux-release ] ; then
          VERSION=`${CATCOMMAND} /etc/UnitedLinux-release | ${TRCOMMAND} "\n" ' ' | ${SEDCOMMAND} s/VERSION.*//`
          ret_getFullDistroName=0
        fi
      fi
    fi
  fi

  if [ $ret_getFullDistroName = 0 ];
  then
    VERSION=`${ECHOCOMMAND} $VERSION | ${SEDCOMMAND} s/.*:\ // | ${SEDCOMMAND} s/release\ // | ${SEDCOMMAND} s:GNU/Linux\ ::`
  fi

  return 0
}

getDistroName()
{
  ret_getDistroName=0

  getFullDistroName
  if [ $ret_getFullDistroName = 0 ];
  then
     VERSION=`${ECHOCOMMAND} $VERSION | ${SEDCOMMAND} s/.*:\ // | ${SEDCOMMAND} s/release\ // | ${SEDCOMMAND} s:GNU/Linux\ :: | ${SEDCOMMAND} s/\(.*\)//`
  fi

  ret_getDistroName=1
  return 0
}

########################################################################################

convertNXconfigToCamelCaseFormat ()
{
$AWKCOMMAND '
function camelCase(key) {
  comment = 0
  if (substr(key, 1,1) == "#") {
    comment = 1
    key = substr(key, 2)
  }
  if (length(key)) {
    split (key, tab, "_")
    i = 1
    key = ""
    keyUpper["SSH"]   = "SSH"
    keyUpper["CUPS"]  = "CUPS"
    keyUpper["TCP"]   = "TCP"
    keyUpper["RDP"]   = "RDP"
    keyUpper["RFB"]   = "RFB"
    keyUpper["DB"]    = "DB"
    keyUpper["SSHD"]  = "SSHD"
    keyUpper["CUPSD"] = "CUPSD"
    keyUpper["DPI"]   = "DPI"
    keyUpper["CDE"]   = "CDE"
    keyUpper["KDE"]   = "KDE"
    keyUpper["IP"]    = "IP"
    keyUpper["WM"]    = "WM"
    keyUpper["NX"]    = "NX"
    keyUpper["PS"]    = "PS"
    keyUpper["NXSSH"] = "NXSSH"

    while (length(tab[i])) {
      if(!(tab[i] in keyUpper)) {
        if (tab[i] == "XKBCOMP") {
          tab[i] = "XkbComp"
        } else if (tab[i] == "XDPYINFO") {
          tab[i] = "XdpyInfo"
        } else if (tab[i] == "NXDIALOG") {
          tab[i] = "NXDialog"
        } else if (tab[i] == "NXNODE") {
          tab[i] = "NXNode"
        } else if (tab[i] == "NXAGENT") {
          tab[i] = "NXAgent"
        } else if (tab[i] == "NXPROXY") {
          tab[i] = "NXProxy"
        } else if (tab[i] == "NXDESKTOP") {
          tab[i] = "NXDesktop"
        } else if (tab[i] == "NXCLIENT") {
          tab[i] = "NXClient"
        } else if (tab[i] == "NXVIEWER") {
          tab[i] = "NXViewer"
        } else if (tab[i] == "NXPASSWD") {
          tab[i] = "NXPasswd"
        } else if (tab[i] == "NXEXEC") {
          tab[i] = "NXexec"
        } else if (tab[i] == "NXSENSOR") {
          tab[i] = "NXSensor"
        } else if (tab[i] == "MKDIR") {
          tab[i] = "MkDir"
        } else if (tab[i] == "LPOPTIONS") {
          tab[i] = "LpOptions"
        } else if (tab[i] == "SETXKBMAP") {
          tab[i] = "SetXkbMap"
        } else if (tab[i] == "PFILES") {
          tab[i] = "PFiles"
        } else if (tab[i] == "KEEPALIVE") {
          tab[i] = "KeepAlive"
        } else {
          tab[i] = tolower(tab[i])
        }
      }
      key = sprintf ("%s%s%s", key , toupper(substr(tab[i],1,1)) , substr(tab[i],2))
      i++
    }
  }
  if (comment) {
    key = sprintf("#%s" , key)
  }
  return key
}
{
FS=" |="
if($0 ~ /^([ \t]*([^=;]+)[ \t]*=[ \t]*"([^"]*))".*/) {
  if($1 ~ /(([A-Z])+_+)/) {
    line = camelCase($1)" = "
    if ($2 != "") { line = line$2" " }
    if ($3 != "") { line = line$3" " }
    if ($4 != "") { line = line$4" " }
    if ($5 != "") { line = line$5" " }
    if ($6 != "") { line = line$6" " }
    if ($7 != "") { line = line$7" " }
    if ($8 != "") { line = line$8" " }

    print line
  } else {
    if ($2 ~ /(([A-Z])+_+)/) {
      line = $1" "camelCase($2)" = "
      if ($3 != "") { line = line$3" " }
      if ($4 != "") { line = line$4" " }
      if ($5 != "") { line = line$5" " }
      if ($6 != "") { line = line$6" " }
      if ($7 != "") { line = line$7" " }
      if ($8 != "") { line = line$8" " }

      print line
    } else {
      print $0
    }
  }
} else {
  print $0
}
}' < "$CONFIG_FILE" >  "$CONFIG_FILE.tmp"

  ${SEDCOMMAND} -e 's|^ConfigFileVersion.*$|ConfigFileVersion = "2.0"|g' "$CONFIG_FILE.tmp" > "$CONFIG_FILE"
}

checkNXconfig ()
{
  printMsgDebug "checkNXconfig (upgrade=${upgrade})"
  printMsg "Creating configuration in: $CONFIG_FILE"

  if [ "x${upgrade}" = "x1" ];
  then
    SHOWUPDATEINFO="yes"
    printMsg "Configuration file needs to be updated" "cmd"
    printMsg "Copying original configuration to $CONFIG_FILE.backup"

    commandBackupFile "$CONFIG_FILE" "backup" "warn"

    if [ "${PACKAGE_NAME}" = "webplayer" ];
    then
      printMsg "Creating new sample configuration file: $NX_ROOT/etc/cloud-$system.cfg.sample"
    else
      printMsg "Creating new sample configuration file: $NX_ROOT/etc/${PACKAGE_NAME}-$system.cfg.sample"
    fi
    printMsg "Updating $CONFIG_FILE file"

    isNewestConfFileVersion
    if [ "x${ret_isNewestConfFileVersion}" != "x1" ];
    then
      upgradeConfigFile
      if [ ${ret_upgradeConfigFile} != 0 ];
      then
        printMsg "Error while checking config file version: ${CONFIG_FILE}" "error"
      fi
    fi

  fi
}

makeNXConfig ()
{
  printMsgDebug "makeNXConfig"

  sourceFile=""

  if [ -f "$CONFIG_FILE" ];
  then
    #in Preview config files has to be replaced
    checkNXconfig
  else
    printMsg "Creating configuration in: $CONFIG_FILE"
    if [ -f "$CONFIG_FILE.update" ];
    then
      sourceFile="$CONFIG_FILE.update"
    else
      if [ "$system" = "ubuntu" ];
      then
        syscfg="debian";
      else
        syscfg=$system;
      fi
      if [ -f "$NX_ROOT/etc/${PACKAGE_NAME}-$syscfg.cfg.sample" ];
      then
        sourceFile="$NX_ROOT/etc/${PACKAGE_NAME}-$system.cfg.sample"
      elif [ "${PACKAGE_NAME}" = "webplayer" ] && \
          [ -f "$NX_ROOT/etc/cloud-$syscfg.cfg.sample" ];
      then
        sourceFile="$NX_ROOT/etc/cloud-$system.cfg.sample"
      else
        printMsg "Cannot create configuration file" "error"
        exit 1
      fi
    fi
  fi

  if ([ "${PACKAGE_NAME}" = "node" ] || [ "${PACKAGE_NAME}" = "server" ]) && \
     [ -e "${sourceFile}" ];
  then
    commandInstall "${USER_NX}" "${ROOTGNAME}" "644" "${sourceFile}" \
                   "${CONFIG_FILE}" "error"
  fi

  if [ "${system}" = "macosx" ];
  then
    commandChmod "1777" "${NX_VAR_DIR}/log" "warn"
  fi
}

resetNXConfig ()
{

  if [ -f "$CONFIG_FILE" ];
  then
    printMsg "Saving configuration file to: $CONFIG_FILE.backup"
    commandBackupFile "$CONFIG_FILE" "backup" "error"
    commandRm "$CONFIG_FILE" "error"
  fi
}

updatePathForCommentedOutSampleValue ()
{
  printMsgDebug "updatePathForCommentedOutSampleValue: ($1,$2)"

   key=$1
   defaultPath="$2"

   if [ "x$defaultPath" = "x" ];
   then
     if [ "$system" = "solaris" ];
     then
       defaultPath="/opt/NX"
     elif [ "$system" = "macosx" ];
     then
       #defaultPath="/Applications/NoMachine Service.app"
       defaultPath="/Applications/NoMachine.app"
     else
       defaultPath="/usr/NX"
     fi
   fi

   if [ "x${defaultPath}" = "x${NX_ROOT}" ];
   then
     return 0
   fi

   $SEDCOMMAND -e 's:^#'"${key}"'\( *[\"]*\)'"${defaultPath}"':'"#${key}\1${NX_ROOT}"':g'  "${CONFIG_FILE}" > "${CONFIG_FILE}".tmp
   commandRestoreFile "$CONFIG_FILE" "tmp"
}

upgradeConfigFile4 ()
{
  new_cfg_file="$1"
  old_cfg_file="$1"

  UPGRADE_CFG_FILE_LOG="${NX_VAR_DIR}/log/"
}

########################################################################################
####  LICENSE
########################################################################################

validateLicenseFile ()
{
  if [ -f "${LICENSE_FILE}.sample" ];
  then
#    if [ "${system}" = "macosx" ];
#    then
#      runCommand "'/Applications/NoMachine.app/Contents/Frameworks/bin/nx${PACKAGE_NAME}' --validate" "Cannot validate license file" "error"
#    else
      runCommand "'/etc/NX/nx${PACKAGE_NAME}' --validate" "Cannot validate license file" "error"
#    fi
  fi
}

removeLicenseSampleFile ()
{
  file_lic="$1"

  if [ "x${file_lic}" = "x" ];
  then
    file_lic="${LICENSE_FILE}"
  fi

  commandRmIfExist "${file_lic}.sample" "error"
}

setPermLicense ()
{
  file_lic="$1"

  if [ "x${file_lic}" = "x" ];
  then
    file_lic="${LICENSE_FILE}"
  fi

  if [ -f "${file_lic}" ];
  then
    commandChownChmod "${USER_NX}:${ROOTGNAME}" "0400" "${file_lic}" "error"
  fi
}

installLicenseFile ()
{
  file_lic="$1"

  if [ "x${file_lic}" = "x" ];
  then
    file_lic="${LICENSE_FILE}"
  fi

  if [ -f "${file_lic}.sample" ];
  then
    commandRmIfExist "${file_lic}" "error"
    commandMv "${file_lic}.sample" "${file_lic}" "error"
  fi

  setPermLicense "${file_lic}"
}


getDirGroupOwner ()
{
  printMsgDebug "getDirGroupOwner: ($1)"
  ret_getDirGroupOwner=0

  directory="$1"
  groupOwner=""

  if [ "x$directory" = "x" ] || [ ! -d "$directory" ];
  then
    printMsg "Cannot stat directory: $directory" "cmd"
    ret_getDirGroupOwner=1

    return 0
  fi

  dir_basename=`${BASENAMECOMMAND} $directory 2>&1`

  if [ "$?" != 0 ];
  then
    printMsg "Error while retrieving basename of: $directory. Error: $dir_basename" "cmd"
    ret_getDirGroupOwner=1

    return 0
  fi

  dir_path=`${DIRNAMECOMMAND} $directory 2>&1`

  if [ "$?" != 0 ];
  then
    printMsg "Error while retrieving dirname of: $directory. Error: $dir_path" "cmd"
    ret_getDirGroupOwner=1

    return 0
  fi

  groupOwner=`${LSCOMMAND} -l $dir_path | ${AWKCOMMAND} -F ' '  '$8 ~ /^'"$dir_basename"'$/ {print $4}' 2>&1`

  if [ "$?" != 0 ] || [ "x$groupOwner" = "x" ];
  then
    printMsg "Cannot check group id of directory: ${directory}. Error: ${groupOwner}" "cmd"

    groupOwner=""
    ret_getDirGroupOwner=1

    return 0
  fi

  return 0
}

isNetworkUser ()
{
  ret_isNetworkUser=0
  networkUserType=""

  if [ "${system}" = "macosx" ];
  then
    return 0
  fi

  user=$1
  checkUserExist ${user}
  checkUserExistPasswd ${user}

  if [ "x$ret_checkUserExist" = "x1" ] && [ "x$ret_checkUserExistPasswd" = "x0" ];
  then
    networkUserType="network"
    ret_isNetworkUser=2

    printMsg "User: ${user} is ${networkUserType} user" "cmd"

    return 0
  fi
}

isInstalledMacPkg ()
{
  ret_isInstalledMacPkg=0

  pkg_name="$1"
  getPackagePath "${pkg_name}"
  if [ ${ret_getPackagePath} = 0 ];
  then
    if [ "x${pkg_name}" = "xplayer" ];
    then
      fileToCheck="${ret_packagePath}/../MacOS/nx${pkg_name}"
    else
      fileToCheck="${ret_packagePath}/bin/nx${pkg_name}"
    fi

    if [ -x "${fileToCheck}" ];
    then
      ret_isInstalledMacPkg=1
      return 0
    fi
  else
    return 0
  fi

  return 0
}

isInstalledOtherMacPackage ()
{
  pkgname="$1"
  ret_isInstalledOtherMacPackage=0

  if [ "x${pkgname}" = "xserver" ];
  then
    isInstalledMacPkg "node"
    ret_isInstalledOtherMacPackage=${ret_isInstalledMacPkg}
    return 0
  fi

  if [ "x${pkgname}" = "xnode" ];
  then
    isInstalledMacPkg "player"
    if [ ${ret_isInstalledMacPkg} = 1 ];
    then
      ret_isInstalledOtherMacPackage=1
      return 0
    fi

    isInstalledMacPkg "server"
    if [ ${ret_isInstalledMacPkg} = 1 ];
    then
      ret_isInstalledOtherMacPackage=1
      return 0
    fi
    return 0
  fi

 if [ "x${pkgname}" = "xplayer" ];
  then
    isInstalledMacPkg "node"
    if [ ${ret_isInstalledMacPkg} = 1 ];
    then
      ret_isInstalledOtherMacPackage=1
      return 0
    fi

    isInstalledMacPkg "server"
    if [ ${ret_isInstalledMacPkg} = 1 ];
    then
      ret_isInstalledOtherMacPackage=1
      return 0
    fi
    return 0
  fi

  return 0
}

isInstalledPackage ()
{
  ret_isInstalledPackage=0

  if [ "x${system}" = "xmacosx" ];
  then
    isInstalledMacPkg ${1}
    ret_isInstalledPackage=${ret_isInstalledMacPkg}
    return 0
  fi

  getConfigFileName ${1} ${1}
  if [ -f "${ret_getConfigFileName}" ]
  then
    ret_isInstalledPackage=1
    return 0
  fi

  return 0
}

isInstalledOtherPackage ()
{
  pkgname="$1"
  ret_isInstalledOtherPackage=0

  if [ "x${system}" = "xmacosx" ];
  then
    isInstalledOtherMacPackage ${1}
    ret_isInstalledOtherPackage=${ret_isInstalledOtherMacPackage}
    return 0
  fi

  if [ "x${pkgname}" = "xserver" ] || [ "x${pkgname}" = "xnode" ];
  then
    isInstalledPackage "player"
    if [ ${ret_isInstalledPackage} = 1 ];
    then
      ret_isInstalledOtherPackage=1
      return 0
    fi
  fi


  if [ "x${pkgname}" = "xplayer" ];
  then
    isInstalledPackage "node"
    if [ ${ret_isInstalledPackage} = 1 ];
    then
      ret_isInstalledOtherPackage=1
      return 0
    fi

    isInstalledPackage "server"
    if [ ${ret_isInstalledPackage} = 1 ];
    then
      ret_isInstalledOtherPackage=1
      return 0
    fi
    return 0

  fi

  return 0
}

addGroupMac ()
{
  NX_GROUP="$1"
  FULLNAME="$2"

  if [ ${UID} -ne 0 ];
  then
    printMsg "Only root can add ${NX_GROUP} group" "error"

    return 1
  fi

  result=`${DSCLCOMMAND} . -read /Groups/${NX_GROUP} PrimaryGroupID  > /dev/null 2>&1`
  gid_nx=$?

  if [ "$gid_nx" = "0" ];
  then
    printMsg "Group: ${NX_GROUP} already exists" "warn"

    return 0
  fi

  MAXID=$(${DSCLCOMMAND} . -list /Groups PrimaryGroupID | ${AWKCOMMAND} '{print $2}' | ${SORTCOMMAND} -ug | ${TAILCOMMAND} -1)
  GROUP_ID=$((MAXID+1))

  runCommand "${DSCLCOMMAND} . -create /Groups/${NX_GROUP}" "Cannot add group: ${NX_GROUP} to the system" "error"
  if [ $? != 0 ];
  then
    return 1
  fi

  printMsg "Group: ${NX_GROUP} added to the system" "cmd"

  runCommand "${DSCLCOMMAND} . create /Groups/${NX_GROUP} RealName ${FULLNAME}" "Cannot set group name for group '${NX_GROUP}' to '${FULLNAME}'." "warn"
  runCommand "${DSCLCOMMAND} . create /Groups/${NX_GROUP} passwd \"*\" " "Cannot disable password for group '${NX_GROUP}'" "warn"
  runCommand "${DSCLCOMMAND} . create /Groups/${NX_GROUP} gid ${GROUP_ID}"  "Cannot set groupID for group '${NX_GROUP}' to '${GROUP_ID}'" "warn"
}

removeGroupMac ()
{
  NX_GROUP="$1"

  if [ ${UID} -ne 0 ];
  then
    printMsg "Only root can remove ${NX_GROUP} group" "error"

    return 1
  fi

  result=`${DSCLCOMMAND} . -read /Groups/${NX_GROUP} PrimaryGroupID  > /dev/null 2>&1`
  gid_nx=$?

  if [ "$gid_nx" != "0" ];
  then
    printMsg "Group: ${NX_GROUP} does not exist" "warn"

    return 0
  fi

  runCommand "${DSCLCOMMAND} . -delete /Groups/${NX_GROUP}" "Cannot remove group: ${NX_GROUP} from the system" "error"

  if [ $? != 0 ];
  then
    return 1
  fi

  printMsg "Group ${NX_GROUP} removed from the system" "cmd"
}

removeNXUserApple ()
{
  user="$1"
  printMsg "Deleting user: ${user} from the system"

  if [ "x${user}" = "x${USER_NX}" ];
  then
    removeUserMacToSSHGroup ${user}
  fi

  result=`${DSCLCOMMAND} . -delete /Users/${user} 2>&1`
  runCommand "${RMCOMMAND} -fr '${NXUSERHOME}/${user}'" "Cannot remove home directory: '${NXUSERHOME}/${user}'" "error"


  if ${GREPCOMMAND} "^${user}:" "/etc/passwd" > /dev/null
  then
    if ${SEDCOMMAND} -e '/^'"${user}"':/d' "/etc/passwd" > "/etc/passwd.backup"
    then
      commandRestoreFile "/etc/passwd" "backup"
    else
      printMsg "Error while detecting user: ${user} from /etc/passwd file" "warn"

      commandRm "/etc/passwd.backup"
    fi
  fi

  removeGroupMac "${user}"

}


MAC_SSH_ACCESS_GROUP="com.apple.access_ssh"

getGroupSSHAccessExistsMac ()
{
  ret_getGroupSSHAccessExistsMac=""

  dscl_out=`${DSCLCOMMAND} . list /Groups | ${GREPCOMMAND} ${MAC_SSH_ACCESS_GROUP} | ${GREPCOMMAND} -v ${MAC_SSH_ACCESS_GROUP}-disabled 2>/dev/null`
  if [ "x${dscl_out}" != "x" ];
  then
    ret_getGroupSSHAccessExistsMac="${MAC_SSH_ACCESS_GROUP}"

    return 0 
  fi

  dscl_out=`${DSCLCOMMAND} . list /Groups | ${GREPCOMMAND} ${MAC_SSH_ACCESS_GROUP}-disabled 2>/dev/null`
  if [ "x${dscl_out}" != "x" ];
  then
    ret_getGroupSSHAccessExistsMac="${MAC_SSH_ACCESS_GROUP}-disabled"

    return 0
  fi
}

addUserMacToSSHGroup ()
{
  user="$1"

  getGroupSSHAccessExistsMac
  if [ "x${ret_getGroupSSHAccessExistsMac}" = "x" ];
  then
    return 0
  fi

  runCommand "${DSCLCOMMAND} . append /Groups/${ret_getGroupSSHAccessExistsMac} GroupMembership ${user}" "Cannot add user ${user} to group ${ret_getGroupSSHAccessExistsMac}" "warn" 
}

removeUserMacToSSHGroup ()
{
  user="$1"

  getGroupSSHAccessExistsMac
  if [ "x${ret_getGroupSSHAccessExistsMac}" = "x" ];
  then
    return 0
  fi

  runCommand "${DSCLCOMMAND} . delete /Groups/${ret_getGroupSSHAccessExistsMac} GroupMembership ${user}" "Cannot remove user ${user} from group ${ret_getGroupSSHAccessExistsMac}" "warn"
}

disableSptlightIndexing ()
{
  user="$1"

  if [ -d "${NXUSERHOME}/${user}" ];
  then
    if [ ! -f "${NXUSERHOME}/${user}/.metadata_never_index" ];
    then
      commandTouch "${NXUSERHOME}/${user}/.metadata_never_index" "warn"
      commandChown "${user}:${user}" "${NXUSERHOME}/${user}/.metadata_never_index" "warn"
    fi
  else
    printMsg "Cannot disable Spotlight indexing for user: ${user}. Home folder ${NXUSERHOME}/${user} doesn't exist" "cmd"
  fi
}

renameKey ()
{
  ${SEDCOMMAND} -e 's/'${1}'/'${2}'/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"
}

removeOptionFromCfg ()
{
  CFG_OPTION="$1"
  FIRST_LINE_OPTION="$2"

  ${SEDCOMMAND} -e '/'"${FIRST_LINE_OPTION}"'/,/^ *#* *'"${CFG_OPTION}"' *=/d' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  ${SEDCOMMAND} -e '/^#$/{ N; /^#\n$/d;}' "${CONFIG_FILE}.tmp" > "${CONFIG_FILE}"

  printMsgRemoveKeyFromConfigFile "${CFG_OPTION}"
}

removeOptionFromCfgNew ()
{
  CFG_OPTION="$1"
  FIRST_LINE_OPTION="$2"

  ${SEDCOMMAND} -e '/'"${FIRST_LINE_OPTION}"'/,/^ *#* *'"${CFG_OPTION}"' */d' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  ${SEDCOMMAND} -e '/^#$/{ N; /^#\n$/d;}' "${CONFIG_FILE}.tmp" > "${CONFIG_FILE}"
  ${SEDCOMMAND} -e '${/^#$/d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  printMsgRemoveKeyFromConfigFile "${CFG_OPTION}"
}

insertKeytoConfigFile ()
{
  key=$1
  key_description=$2
  insert_after=$3

  command="${GREPCOMMAND} '\(#\)\?'${key}' *= ' '${CONFIG_FILE}'"
  outCommand=`${BASHSHELL} -c "${command}" 2>&1`
  if [ $? = 0 ];
  then
    printMsg "Key: ${key} already exists in config file. Not inserted" "cmd"
    return
  fi

  command="${GREPCOMMAND} '\(#\)\?'${key}' ' '${CONFIG_FILE}'"
  outCommand=`${BASHSHELL} -c "${command}" 2>&1`
  if [ $? = 0 ];
  then
    printMsg "Key: ${key} already exists in config file. Not inserted" "cmd"
    return
  fi

  if [ "${system}" != "solaris" ];
  then
    if [ "x${insert_after}" != "x" ];
    then
      ${AWKCOMMAND} '
      FNR==NR && /'${insert_after}'/ { line=NR; next }
      FNR!=NR
      FNR==line { print "'"${key_description}"'" }
      ' "${CONFIG_FILE}" "$CONFIG_FILE" > "${CONFIG_FILE}.tmp"
      commandRestoreFile "${CONFIG_FILE}" "tmp"
    fi
  fi

  command="${GREPCOMMAND} '\(#\)\?'${key}' ' '${CONFIG_FILE}'"
  outCommand=`${BASHSHELL} -c "${command}" 2>&1`
  if [ $? != 0 ];
  then
    printMsg "Key: ${key} added at the end of file" "onlylog"
    if [ "${system}" != "solaris" ];
    then
      ${ECHOCOMMAND} -e "${key_description}"  >> "${CONFIG_FILE}"
    else
      ${ECHOCOMMAND} "${key_description}"  >> "${CONFIG_FILE}"
    fi
  else
    printMsg "Inserted key: ${key}" "onlylog"
  fi

  outCommand=`${BASHSHELL} -c "${command}" 2>&1`
  if [ $? != 0 ];
  then
    printMsgAddKeyToConfigFile "${key}"
  fi
}

insertSectiontoConfigFile ()
{
  first_line="${1}"
  key_description="${2}"
  insert_after="${3}"

  if [[ `${GREPCOMMAND} "${first_line}" "${CONFIG_FILE}"` ]]
  then
    printMsg "Section: \"${first_line}\" already exists in config file. Not inserted" "cmd"
    return
  fi

  if [ "${system}" != "solaris" ]
  then
    if [ "x${insert_after}" != "x" ]
    then

      ${AWKCOMMAND} '
      FNR==NR && /'${insert_after}'/ { line=NR; next }
      FNR!=NR
      FNR==line { print "'"${key_description}"'" }
      ' "${CONFIG_FILE}" "$CONFIG_FILE" > "${CONFIG_FILE}.tmp"

      commandRestoreFile "${CONFIG_FILE}" "tmp"

    else
      ${ECHOCOMMAND} -e "${key_description}"  >> "${CONFIG_FILE}"
    fi
  else
    ${ECHOCOMMAND} "${key_description}" >> "${CONFIG_FILE}"
  fi

  if [[ ! `${GREPCOMMAND} "${first_line}" "${CONFIG_FILE}"` ]]
  then
    printMsg "Section: \"${first_line}\" not added" "warn"
  fi
}

upgradeKey ()
{
  key=$1
  leave_quotation=$2

  command="${GREPCOMMAND} '[#]*'${key}' *= ' '${CONFIG_FILE}'"
  outCommand=`${BASHSHELL} -c "${command}" 2>&1`
  if [ $? = 0 ];
  then
    if [ "${leave_quotation}" = "1" ];
    then
      ${SEDCOMMAND} -e 's|'${key}' *= *\(.*\)|'${key}' \1|' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    else
      ${SEDCOMMAND} -e 's|'${key}' *= [\"]*\(.*\)[\"]|'${key}' \1|' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    fi

    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

}

##########################################################################
############################  XDG  #######################################
##########################################################################
if [ "x${NX_MPKG_PACKAGE}" = "xserver" ];
then
  menu_suffix=""
elif [ "x${NX_MPKG_PACKAGE}" = "xnode" ] &&  [ "x${PACKAGE_NAME}" = "xserver" ];
then
  # use nxserver resources
  menu_suffix=""
else
  menu_suffix="-${PACKAGE_NAME}"
fi


installResources ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  printMsgDebug "Resources: install"

  isInstalledXDG
  if [ ${ret_isInstalledXDG} = 0 ];
  then
    __installResourcesXDG__
  else
    __installResources__
  fi
}

updateResources ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  printMsgDebug "Resources: update"

  uninstallResources
  installResources
}

uninstallResources ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  printMsgDebug "Resources: uninstall"

  isInstalledXDG
  if [ ${ret_isInstalledXDG} = 0 ];
  then
    __uninstallResourcesXDG__
  else
    __uninstallResources__
  fi
}


isInstalledXDG ()
{
  `${XDGOPENCOMMAND} --version > /dev/null 2>&1`
  ret_isInstalledXDG=$?
}

setIconVariables ()
{
  THEME_DIR="/usr/share/icons/hicolor"
}

installIcon ()
{
  icon_file=$1

  ret_installIcon=0

  for size in 16 22 32 48;
  do
    icon_file_path="${NX_ROOT}/share/icons/${size}x${size}/${icon_file}"

    if [ -f ${icon_file_path} ];
    then
      commandCp "${icon_file_path}" "${THEME_DIR}/${size}x${size}/apps/"
    else
      printMsgDebug "Cannot install icon: ${icon_file}. Cannot stat file."
      ret_installIcon=1
    fi
  done
}

removeIcon ()
{
  icon_file=$1

  ret_removeIcon=0

  for size in 16 22 32 48; do

    commandRmIfExist "${THEME_DIR}/${size}x${size}/apps/${icon_file}" "warn"

  done
}

installXDGIcon ()
{
  icon_file=$1
  icon_name=$2

  for size in 16 22 32 48;
  do
    icon_file_path="${NX_ROOT}/share/icons/${size}x${size}/${icon_file}"

    if [ -f ${icon_file_path} ];
    then

      xdgDataDirs="$XDG_DATA_DIRS:/usr/local/share:/usr/share"

      old_icon_fileMD5=""

      while [ "x${xdgDataDirs}" != "x" ] && [ "x${old_icon_fileMD5}" = "x" ];
      do
        currentDir=`${ECHOCOMMAND} "$xdgDataDirs" | ${CUTCOMMAND} -d ':' -f 1`
        xdgDataDirs=`${ECHOCOMMAND} "$xdgDataDirs" | ${CUTCOMMAND} -s -d ':' -f 2-`

        old_icon_fileMD5=`${FINDCOMMAND} "${currentDir}/icons/hicolor/$size"x"$size/apps/" -name\
                             "${icon_file}" -exec ${MD5SUMCOMMAND} {} \; 2>/dev/null | ${CUTCOMMAND} -b -32`

      done

      new_icon_fileMD5=`${MD5SUMCOMMAND} "${icon_file_path}" | ${CUTCOMMAND} -b -32`

      if [ "x${old_icon_fileMD5}" != "x${new_icon_fileMD5}" ];
      then
        ret_updateXDGIcons="1";

        (${XDGICONRESOURCECOMMAND} install --noupdate --context apps --mode\
                                   system --size "${size}" "${icon_file_path}" "${icon_name}" >> "${LOGFILE}" 2>&1 ) &

      fi
    else
      printMsgDebug "Cannot install icon: ${icon_name}. Cannot stat file."

      ret_installXDGIcon=1
    fi
  done

  wait
}

removeXDGIcon ()
{
  icon_name=$1
  printMsg "Removing XDG Icons" "cmd"
  ret_removeXDGIcons=0

  for size in 16 22 32 48;
  do
    (${XDGICONRESOURCECOMMAND} uninstall --context apps --mode system --size "${size}" "${icon_name}" >> "${LOGFILE}" 2>&1 ) &
  done

  wait
}

createXDGMime ()
{
  printMsg "Installing XDG Mime" "cmd"

  mime_file="$1"

  if [ ! -f "${mime_file}" ];
  then
    printMsg "Cannot install Mime. File not found: ${mime_file}." "cmd"
  fi

  (${XDGMIMECOMMAND} install --mode system "${mime_file}" >> "${LOGFILE}" 2>&1 ) &

  ret_createXDGMime=0
}

removeXDGMime ()
{
  mime_file="$1"

  printMsg "Removing XDG Mime" "cmd"
  ret_removeXDGMime=0

  if [ -f "${mime_file}" ];
  then
    #runCommand "${XDGMIMECOMMAND} uninstall --mode system '${mime_file}'" "Cannot remove mime '${mime_file}'" "cmd"
    #ret_removeXDGMime=${ret_runCommand}
    (${XDGMIMECOMMAND} uninstall --mode system "${mime_file}" >> "${LOGFILE}" 2>&1 ) &
    ret_removeXDGMime=0
  fi
}

adaptDesktopFiles ()
{
  if [ "${NX_ROOT}" != "/usr/NX" ]
  then
    if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-base.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-base.desktop.tmp"
    then
      commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-base.desktop" "tmp" "warn"
    fi

    if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop.tmp"
    then
      commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop" "tmp" "warn"
    fi

    if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-base-xfce.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-base-xfce.desktop.tmp"
    then
      commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-base-xfce.desktop" "tmp" "warn"
    fi


    if [ "x${PACKAGE_NAME}" = "xserver" ];
    then
      #if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-pref.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-pref.desktop.tmp"
      #then
      #  commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-pref.desktop" "tmp" "warn"
      #fi

      #if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-pref-unity.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-pref-unity.desktop.tmp"
      #then
      #  commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-pref-unity.desktop" "tmp" "warn"
      #fi

      if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-status.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-status.desktop.tmp"
      then
        commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-status.desktop" "tmp" "warn"
      fi

      if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-status-unity.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-status-unity.desktop.tmp"
      then
        commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-status-unity.desktop" "tmp" "warn"
      fi

      if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine${menu_suffix}-status-xfce.desktop" > "${NX_XDG}/NoMachine${menu_suffix}-status-xfce.desktop.tmp"
      then
        commandRestoreFile "${NX_XDG}/NoMachine${menu_suffix}-status-xfce.desktop" "tmp" "warn"
      fi

    fi

  fi  
}

setMenuVariables ()
{
  APPLICATIONS_DIR="/usr/share/applications/"

  APPLICATIONSMERGED_DIR="/etc/xdg/menus/applications-merged/"

  DESKTOPDIRS_DIR="/usr/share/desktop-directories/"  
}

createMenuEntries ()
{
  printMsg "Creating menu applications entries" "cmd"

  ret_createMenuEntries=0

  setMenuVariables

  adaptDesktopFiles

  if [ -w "${APPLICATIONS_DIR}" ];
  then

    commandCp "${NX_XDG}/NoMachine${menu_suffix}-base.desktop" "${APPLICATIONS_DIR}" "warn"
    commandCp "${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop" "${APPLICATIONS_DIR}" "warn"
    commandCp "${NX_XDG}/NoMachine${menu_suffix}-base-xfce.desktop" "${APPLICATIONS_DIR}" "warn"

    if [ "x${PACKAGE_NAME}" = "xserver" ];
    then
      commandCp "${NX_XDG}/NoMachine${menu_suffix}-status.desktop" "${APPLICATIONS_DIR}" "warn"
      commandCp "${NX_XDG}/NoMachine${menu_suffix}-status-unity.desktop" "${APPLICATIONS_DIR}" "warn"
      commandCp "${NX_XDG}/NoMachine${menu_suffix}-status-xfce.desktop" "${APPLICATIONS_DIR}" "warn"
    fi

  fi

  if [ -w "${DESKTOPDIRS_DIR}" ];
  then
    commandCp "${NX_XDG}/NoMachine${menu_suffix}-dir.directory" "${DESKTOPDIRS_DIR}" "warn"
  fi

  if [ -w "${APPLICATIONSMERGED_DIR}" ];
  then
    commandCp "${NX_XDG}/NoMachine${menu_suffix}-dir.menu" "${APPLICATIONSMERGED_DIR}" "warn"
  fi
}

removeMenuEntries ()
{
  printMsg "Removing menu applications entries" "cmd"

  ret_removeMenuEntries=0

  setMenuVariables

  commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-base.desktop" "warn"
  commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-base-unity.desktop" "warn"
  commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-base-xfce.desktop" "warn"

  if [ "x${PACKAGE_NAME}" = "xserver" ];
  then
    commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-status.desktop" "warn"
    commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-status-unity.desktop" "warn"
    commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-status-xfce.desktop" "warn"
  fi

  commandRmIfExist "${DESKTOPDIRS_DIR}/NoMachine${menu_suffix}-dir.directory" "warn"

  commandRmIfExist "${APPLICATIONSMERGED_DIR}/NoMachine${menu_suffix}-dir.menu" "warn"

}

createXDGMenu ()
{

  if [ "x${NX_MPKG_PACKAGE}" != "x${PACKAGE_NAME}" ];
  then
    if [ "x${NX_MPKG_PACKAGE}" != "xnode" ] || [ "x${PACKAGE_NAME}" != "xserver" ];
    then
      return 0
    fi 
  fi

  printMsg "Creating XDG Menu" "cmd"
  ret_createXDGMenu=0

#  updateMenuItemName
#  if [ $ret_updateMenuItemName != 0 ];
#  then
#    printMsg "Error while updating XDG Menu item names" "warn"
#    ret_createXDGMenu=1
#    return 0
#  fi

  adaptDesktopFiles

  if [ "x${PACKAGE_NAME}" = "xserver" ];
  then
    #runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine${menu_suffix}-dir.directory' '${NX_XDG}/NoMachine${menu_suffix}-base.desktop' '${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop' '${NX_XDG}/NoMachine${menu_suffix}-pref.desktop' '${NX_XDG}/NoMachine${menu_suffix}-pref-unity.desktop' '${NX_XDG}/NoMachine${menu_suffix}-status.desktop' '${NX_XDG}/NoMachine${menu_suffix}-status-unity.desktop'" "Cannot install server status menu" "cmd"
    runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine${menu_suffix}-dir.directory' '${NX_XDG}/NoMachine${menu_suffix}-base.desktop' '${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop' '${NX_XDG}/NoMachine${menu_suffix}-status.desktop' '${NX_XDG}/NoMachine${menu_suffix}-status-unity.desktop'" "Cannot install server status menu" "cmd"

    runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine${menu_suffix}-base-xfce.desktop' '${NX_XDG}/NoMachine${menu_suffix}-status-xfce.desktop'" "Cannot install server status menu" "cmd"
  else
    runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine${menu_suffix}-dir.directory' '${NX_XDG}/NoMachine${menu_suffix}-base.desktop' '${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop'" "Cannot install menu '${NX_XDG}/NoMachine${menu_suffix}-dir.directory'" "cmd"

    runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine${menu_suffix}-base-xfce.desktop'" "Cannot install menu '${NX_XDG}/NoMachine${menu_suffix}-dir.directory'" "cmd"
    #(${XDGDESKTOPMENUCOMMAND} install --mode system "${NX_XDG}/NoMachine${menu_suffix}-dir.directory" "${NX_XDG}/NoMachine${menu_suffix}-base.desktop" "${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop" >> "${LOGFILE}" 2>&1 ) &

  fi

  #if [ ${ret_runCommand} != 0 ];
  #then
  #  removeXDGMenu
  #  ret_createXDGMenu=1
  #  return 0
  #fi

  return 0
}

removeXDGMenu ()
{
  ret_removeXDGMenu=0

  if [ "x${NX_MPKG_PACKAGE}" != "x${PACKAGE_NAME}" ];
  then
    if [ "x${NX_MPKG_PACKAGE}" != "xnode" ] || [ "x${PACKAGE_NAME}" != "xserver" ];
    then
      return 0
    fi
  fi

  printMsg "Removing XDG Menu" "cmd"

  if [ "x${PACKAGE_NAME}" = "xserver" ];
  then
    runCommand "${XDGDESKTOPMENUCOMMAND} uninstall --mode system  NoMachine${menu_suffix}-dir.directory NoMachine${menu_suffix}-base.desktop NoMachine${menu_suffix}-base-unity.desktop NoMachine${menu_suffix}-base-xfce.desktop NoMachine${menu_suffix}-status.desktop NoMachine${menu_suffix}-status-unity.desktop NoMachine${menu_suffix}-status-xfce.desktop" "Cannot uninstall server status menu" "cmd"

    #remove nxplayer leftovers
    out=`${XDGDESKTOPMENUCOMMAND} uninstall --mode system NoMachine-player-dir.directory NoMachine-player-base.desktop NoMachine-player-base-unity.desktop NoMachine-player-base-xfce.desktop > /dev/null 2>&1`
  else
    runCommand "${XDGDESKTOPMENUCOMMAND} uninstall --mode system NoMachine${menu_suffix}-dir.directory NoMachine${menu_suffix}-base.desktop NoMachine${menu_suffix}-base-unity.desktop NoMachine${menu_suffix}-base-xfce.desktop" "Cannot uninstall menu 'NoMachine${menu_suffix}-dir.directory'" "cmd"
  ret_removeXDGMenu=${ret_runCommand}
  fi

  #(${XDGDESKTOPMENUCOMMAND} uninstall --mode system NoMachine${menu_suffix}-dir.directory NoMachine${menu_suffix}-base.desktop NoMachine${menu_suffix}-base-unity.desktop >> "${LOGFILE}" 2>&1 ) &
  #ret_removeXDGMenu=0

}

updateXDGMenuFile ()
{
  menuFile=$1

  ret_updateXDGMenuFile=0
  menuFullNameFile=""

  if [ "x${XDG_CONFIG_DIRS}" != "x" ];
  then
    menuFullNameFile="${XDG_CONFIG_DIRS}/menus/applications-merged/${menuFile}"

    if [ ! -f "${menuFullNameFile}" ];
    then
      printMsg "Cannot stat ${menuFullNameFile} file. Trying '/etc/xdg'" "cmd"
      menuFullNameFile=""
    fi
  fi

  if [ "x${menuFullNameFile}" = "x" ];
  then
    menuFullNameFile="/etc/xdg/menus/applications-merged/${menuFile}"

    if [ ! -f "${menuFullNameFile}" ];
    then
      printMsg "Cannot stat ${menuFullNameFile} file" "cmd"
      menuFullNameFile=""
      ret_updateXDGMenuFile=1

      return 0
    fi
  fi

  printMsg "XDG Menu file: ${menuFullNameFile}" "cmd"

  menuName=${menuFile%.menu}

  $SEDCOMMAND -e 's/<Name>'"$menuName"'<\/Name>/  <Name>Internet<\/Name>\n      <Menu>\n      <Name>'"$menuName"'<\/Name>/' $menuFullNameFile > $menuFullNameFile.bkp

  if [ $? = 0 ];
  then
    commandMv "${menuFullNameFile}.bkp" "${menuFullNameFile}"

    if [ ${ret_runCommand} = 0 ];
    then
      ${ECHOCOMMAND} "</Menu>" >> ${menuFullNameFile}
      printMsg "Updated XDG menu file '${menuFullNameFile}'" "cmd"
    else
      printMsg "Error while restoring ${menuFullNameFile} file" "warn"
      ret_updateXDGMenuFile=1

      return 0
    fi
  else
    printMsg "Error while updating ${menuFullNameFile} file" "warn"

    ret_updateXDGMenuFile=1

    return 0
  fi

  return 0
}

installXDGMenu ()
{
  printMsg "Installing with XDG" "cmd"
  ret_installXDGMenu=0


  shareNXPath="$NX_ROOT/share"
  shareTmpPath="/tmp/nxshare"
  space=`${ECHOCOMMAND} "$NX_ROOT" | $AWKCOMMAND '{print $2}'`
  if [ "x$space" != "x" ];
  then
    #printMsg "XDG path contain spaces. Creation symlink: ${shareTmpPath}" "cmd"
    runCommand "${LNCOMMAND} -s '${shareNXPath}' '${shareTmpPath}'" "Cannot create symlink for '${shareNXPath}'" "cmd"
    if [ ${ret_runCommand} != 0 ]
    then
      ret_installXDGMenu=1
      return 0
    fi
    shareNXPath="$shareTmpPath"
  fi

  createXDGMenu
  if [ $ret_createXDGMenu != 0 ];
  then
    printMsg "Error while installing XDG menu: $ret" "cmd"
    ret_installXDGMenu=1
    return 0
  fi

  updateXDGMenuFile "NoMachine${menu_suffix}-dir.menu"
  if [ $ret_updateXDGMenuFile != 0 ];
  then
    printMsg "Error while updating XDG menu: $ret" "cmd"
    ret_installXDGMenu=1
    return 0
  fi

  if [ "x$space" != "x" ];
  then
    runCommand "${UNLINKCOMMAND} '$shareTmpPath'" "Cannot remove symlink for '$shareTmpPath'" "cmd"
  fi


  return 0
}

uninstallXDGMenu ()
{
  printMsg "Uninstallation XDG" "cmd"
  ret_uninstallXDGMenu=0

  removeXDGMenu
  if [ $ret_removeXDGMenu != 0 ];
  then
    printMsg "Error while removing XDG menu" "warn"
    ret_uninstallXDGMenu=1
  fi

}

##############################################################################################################

getMacOSXVersion ()
{
  ret_getMacOSXVersion=0

  if [ "x${system}" != "xmacosx" ];
  then
    return 0
  fi

  mac_ver_full=`${SWVERSCOMMAND} -productVersion`
  mac_ver_major=`${SWVERSCOMMAND} -productVersion | ${AWKCOMMAND} -F '\.' '{print $1}'`
  mac_ver_minor=`${SWVERSCOMMAND} -productVersion | ${AWKCOMMAND} -F '\.' '{print $2}'`

  if [ "x${mac_ver_full}" = "x" ];
  then
    printMsg "Cannot read OS version" "cmd"
    ret_getMacOSXVersion=1
    return 0
  fi

  if [ "x${mac_ver_major}" = "x" ];
  then
    printMsg "Cannot read major OS version: ${mac_ver_full}" "cmd"
    ret_getMacOSXVersion=1
    return 0
  fi

  if [ "x${mac_ver_minor}" = "x" ];
  then
    printMsg "Cannot read minor OS version: ${mac_ver_full}" "cmd"
    ret_getMacOSXVersion=1
    return 0
  fi

  return 0
}

hideMacUser ()
{
  user=$1

  ret_hideMacUser=0
  getMacOSXVersion

  if [ ${ret_getMacOSXVersion} -ne 0 ];
  then
    ret_hideMacUser=1
    return 0
  fi

  if [ ${mac_ver_minor} -ge 5 ];
  then
    runCommand "/usr/bin/defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array-add ${user}" "Cannot hide user: ${user}" "warn"
  else
    runCommand "/usr/bin/defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array ${user}" "Cannot hide user: ${user}" "warn"
  fi
}

startNXServerByOtherProduct ()
{
  printMsgDebug "startNXServerByOtherProduct: ()"
#  getPackagePath "server"
#  if [ ${ret_getPackagePath} = 0 ];
#  then
#    startNXServer
#  fi

  if [ -x /etc/NX/nxserver ];
  then
    startNXServer
  fi
}

runAgentApple ()
{
  if [ "${system}" != "macosx" ];
  then
    return 0
  fi

  if [ -f "/Library/LaunchAgents/com.nomachine.agent.plist" ];
  then
    printMsg "Found agent file in: '/Library/LaunchAgents/com.nomachine.agent.plist'" "onlylog"

    ver=`${SWVERSCOMMAND} | ${GREPCOMMAND} 'ProductVersion:' | ${AWKCOMMAND} -F '\.' '{print $2}'`

    if [ $ver -ge 7 ]
    then
      runAgentApple_command=`${PSCOMMAND} aux | ${GREPCOMMAND} loginwindow.app | ${GREPCOMMAND} -v grep | ${GREPCOMMAND} "loginwindow\( console\)*$" | ${AWKCOMMAND} -v cmdsudo=${SUDOCOMMAND} -v cmdlaunch=${LAUNCHCTLCOMMAND} '{print (cmdsudo " " cmdlaunch " bsexec "$2" " cmdsudo " -u "$1" " cmdlaunch " load -S Aqua /Library/LaunchAgents/com.nomachine.agent.plist")}'`

      for ((i=0;i<${#runAgentApple_command[@]};i++)); do
        runCommand "${runAgentApple_command[${i}]}" "Cannot load launchd nxagent file: /Library/LaunchAgents/com.nomachine.agent.plist" "error"
      done

    else
          user=`${PSCOMMAND} aux | ${GREPCOMMAND} loginwindow.app | ${GREPCOMMAND} -v grep | ${GREPCOMMAND} -m 1 loginwindow.app |${AWKCOMMAND} '{print $1}'`
      runAgentApple_command="${SUCOMMAND} -l ${user} -c '${LAUNCHCTLCOMMAND} load -S Aqua /Library/LaunchAgents/com.nomachine.agent.plist'"
      out=`${BASHSHELL} -c "${runAgentApple_command}" 2>&1`

      printMsg "Running: ${runAgentApple_command}" "cmd"
      result=`${ECHOCOMMAND} "${out}" | ${GREPCOMMAND} -c "Socket is not connected" 2>&1`
      if [ ${result} != 0 ];
      then
        printMsg "Result: ${out}" "cmd"
        printMsg "Error while loading launchd nxagent file: /Library/LaunchAgents/com.nomachine.agent.plist" "warn"
      else
        printMsg "Result: OK" "cmd"
      fi
    fi
  else
    printMsg "Cannot stat nxagent plist file: /Library/LaunchAgents/com.nomachine.agent.plist" "error"
  fi
}

enableInitServiceScript ()
{
  ret_enableInitServiceScript=0

  if [ -x ${INSSERVCOMMAND} ];
  then
    runCommand "${INSSERVCOMMAND} -d /etc/init.d/$1" "Cannot enable init service script: $1" "warn"
    ret_enableInitServiceScript=${ret_runCommand}
  fi
}

removeInitServiceScript ()
{
  if [ "x${system}" = "xmacosx" ] || [ "x${system}" = "xsolaris" ];
  then
    return 0
  fi

  tmp=""

  if [ -x ${CHKCONFIGCOMMAND} ];
  then
    printMsg "Running: chkconfig to remove init script: $1" "cmd"
    tmp=`${CHKCONFIGCOMMAND} --del $1 2>&1`
  elif [ -x ${INSSERVCOMMAND} ];
  then
    printMsg "Running: innserv to remove init script: $1" "cmd"
    tmp=`${INSSERVCOMMAND} -r $1 2>&1`
  fi

  if [ "${tmp_nxd}" != "" ]
  then
    printMsg "${tmp_nxd}" "cmd"
  fi
}

foundSystemdDirectory ()
{
  if [ -d "/lib/systemd/system" ];
  then
    SYSTEMD_DIRECTORY="/lib/systemd/system"
  elif [ -d "/usr/lib/systemd/system" ];
  then
    SYSTEMD_DIRECTORY="/usr/lib/systemd/system"
  else
    SYSTEMD_DIRECTORY=""
  fi
}

isSystemdUnitLoaded ()
{
  systemdFile="${1}"
  ret_isSystemdUnitLoaded=""

  ret_isSystemdUnitLoaded=`${SYSTEMCTLCOMMAND} is-enabled ${systemdFile} 2>/dev/null`
  return 0 
}

isSystemDSupported ()
{
  ret_isSystemDSupported=0

  foundSystemdDirectory

  if [ -x "${SYSTEMCTLCOMMAND}" ] && [ "x${SYSTEMD_DIRECTORY}" != "x" ];
  then
    if [ -f /proc/1/exe ];
    then
      result=`${READLINKCOMMAND} /proc/1/exe | ${GREPCOMMAND} systemd 2>/dev/null`
      if [ "x${result}" != "x" ];
      then
        ret_isSystemDSupported=1
        return 0
      fi
    fi
  fi

  return 0
}

replaceNXSystemDService ()
{
  systemdFile="nxserver.service"
  foundSystemdDirectory

  commandRm "${SYSTEMD_DIRECTORY}/${systemdFile}" "error"
  commandCp "${NX_ROOT}/scripts/systemd/${systemdFile}" "${SYSTEMD_DIRECTORY}"/ "error"

  ${SYSTEMCTLCOMMAND} daemon-reload
}

removeNXSystemDService ()
{
  systemdFile="$1"

  isSystemdUnitLoaded ${systemdFile}
  if [[ ${ret_isSystemdUnitLoaded} = "enabled" ]]; 
  then
    stopSystemDService ${systemdFile}
  fi
  if [ -f "${SYSTEMD_DIRECTORY}/${systemdFile}" ];
  then
      commandRm "${SYSTEMD_DIRECTORY}/${systemdFile}" "error"
  fi

  return 0
}

addNXSystemDService ()
{
  systemdFile="$1"
  runService="$2"

  if [ -f "${SYSTEMD_DIRECTORY}/${systemdFile}" ];
  then
    stopSystemDService ${systemdFile}
  fi

  commandCp "${NX_ROOT}/scripts/systemd/${systemdFile}" "${SYSTEMD_DIRECTORY}"/ "error"
  commandRestoreCon "${SYSTEMD_DIRECTORY}/${systemdFile}"

  if [ "x${ret_commandCp}" = "x0" ];
  then
    startSystemDService ${systemdFile} ${runService}
  fi

  return 0
}

startSystemDService ()
{
  service="$1"
  runService="$2"
 
  runCommand "${SYSTEMCTLCOMMAND} enable ${service}" "Cannot enable systemd service: $1" "error"
  if [ "x${runService}" = "x1" ];
  then
    runCommand "${SYSTEMCTLCOMMAND} start $1" "Cannot start systemd service: $1" "error"
  fi
}

stopSystemDService ()
{
  runCommand "${SYSTEMCTLCOMMAND} stop $1" "Cannot stop systemd service: $1" "error"
  if [ $ret_runCommand != 0 ];
  then
    runCommand "${SYSTEMCTLCOMMAND} disable $1" "Cannot disable systemd service: $1" "error"
  fi
}

setNxuexecPermisions ()
{

  if [ -f "${WRAPPER}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "555" "${WRAPPER}" "error"
  else
    printMsg "No such file: ${WRAPPER}" "error"
    exit 1
  fi

}

setNxFsmPermisions ()
{

  if [ -f "${NX_ROOT}/bin/nxfsm" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "555" "${NX_ROOT}/bin/nxfsm" "error"
  fi

}

getGroupOwnerCertsDir ()
{
  ret_getGroupOwnerCertsDir=0

  for certs_dir in ${CUPS_CERTS_DIR[@]};
  do

    getDirGroupOwner "${certs_dir}"

    if [ "$ret_getDirGroupOwner" = "0" ];
    then    

      printMsg "CUPS SystemGroup: ${groupOwner}. Base on directory: ${certs_dir}" \
                                                                            "cmd"   

      return 0
    fi
  done

  ret_getGroupOwnerCertsDir=1

  return 0
}

getCupsBackend ()
{
  if [ "x${CUPS_BACKEND}" = "x" ];
  then
    for tmp in "${CUPS_PATH[@]}"; do
      if test -d "${tmp}/cups/backend" ;
      then
        CUPS_BACKEND="${tmp}/cups/backend";
        break;
      elif test -d "${tmp}/lib64/cups/backend" ;
      then
        CUPS_BACKEND="${tmp}/lib64/cups/backend";
        break;
      elif test -d "${tmp}/lib/cups/backend" ;
      then
        CUPS_BACKEND="${tmp}/lib/cups/backend";
        break;
      elif test -d "${tmp}/cups/lib/cups/backend" ;
      then
        CUPS_BACKEND="${tmp}/cups/lib/cups/backend";
        break;
      fi
    done
  fi
}

removePrintSetup ()
{
  ret_removePrintSetup=0

  CUPS_BACKEND=""
  tmp=""

  if [ "${PACKAGE_NAME}" != "client" ] && [ "${PACKAGE_NAME}" != "devices" ] &&
     [ "${PACKAGE_NAME}" != "node" ];
  then
    return 0
  fi

  if [ "${PACKAGE_NAME}" = "node" ];
  then
    if [ ! -r "${CONFIG_FILE}" ];
    then
      ret_removePrintSetup=1
      return 0
    fi

    getValueFromCfgFile "${CONFIG_FILE}" "CUPSBackendPath"
    if [ ${ret_getValueFromCfgFile} = 2 ];
    then
      tmp=${cfg_val}
    fi
  fi

  getCupsBackend

  if [ "${PACKAGE_NAME}" = "node" ];
  then
    skip_uninstall_print=0
    if [ "${NX_MPKG_PACKAGE}" = "node" ];
    then
      isInstalledPackage "server"
      skip_uninstall_print=${ret_isInstalledPackage}
    else
      isInstalledPackage "node"
      skip_uninstall_print=${ret_isInstalledPackage}
    fi

    if [ ${skip_uninstall_print} = 0 ];
    then
      if [ "x${CUPS_BACKEND}" != "x" ];
      then
        if [ -x "${CUPS_BACKEND}/nx" ];
        then
          commandRm "${CUPS_BACKEND}/nx" "cmd"
          if [ "${CUPS_BACKEND}" = "/usr/lib64/cups/backend" ];
          then
            if [ -x "/usr/lib/cups/backend/nx" ];
            then
              commandRm "/usr/lib/cups/backend/nx" "cmd"
            fi
          fi
        fi
      else
        printMsg "Cannot find cups/backend directory to remove nxdriver for cups" "cmd"
      fi
    else
      printMsg "Skipping uninstalling cups/backend" "cmd"
    fi

  else

    isInstalledOtherPackage "${NX_MPKG_PACKAGE}"

    if [ ${ret_isInstalledOtherPackage} = 0 ];
    then
      if [ -x "${CUPS_BACKEND}/nxprint" ];
      then
        commandRm "${CUPS_BACKEND}/nxprint" "cmd"

        if [ "${CUPS_BACKEND}" = "/usr/lib64/cups/backend" ];
        then
          if [ -x "/usr/lib/cups/backend/nxprint" ];
          then
            commandRm "/usr/lib/cups/backend/nxprint" "cmd"
          fi
        fi
      fi
    else
      printMsg "Skipping uninstalling backend/nxprint" "cmd"
    fi
  fi
}

nxPrintSetup ()
{
  ret_nxPrintSetup=0

  if [ "${PACKAGE_NAME}" != "client" ] && [ "${PACKAGE_NAME}" != "devices" ] &&
     [ "${PACKAGE_NAME}" != "node" ];
  then
    return 0
  fi

  CUPS_BACKEND=""
  tmp=""

  if [ "${PACKAGE_NAME}" = "node" ];
  then
    getValueFromCfgFile "${CONFIG_FILE}" "CUPSBackendPath"
    if [ ${ret_getValueFromCfgFile} = 2 ];
    then
      tmp=${cfg_val}
    fi
  fi

  if [ "x${tmp}" != "x" ];
  then
    if [ -d "${tmp}" ];
    then
      CUPS_BACKEND="${tmp}"
    fi
  fi

  if [ "${PACKAGE_NAME}" = "node" ];
  then
    if [ ! -x "${NXSPOOL}" ];
    then
      printMsg "Cannot find file: ${NXSPOOL}" "cmd"
      ret_nxPrintSetup=1
      return 0
    fi
  else
    if [ ! -x "${NXPRINT}" ];
    then
      printMsg "Cannot find file: ${NXPRINT}" "warn"
      ret_nxPrintSetup=1
      return 0
    fi
  fi

  getCupsBackend

  if [ "x${CUPS_BACKEND}" != "x" ];
  then
    if [ "${PACKAGE_NAME}" = "node" ];
    then
      if [ -x "${CUPS_BACKEND}/nx" ];
      then
        SHOWCUPSINFO="no"
      else
        commandInstall "root" "${ROOTGNAME}" "755" "${NXSPOOL}" "${CUPS_BACKEND}/nx" "Cannot install nx cups backend in directory:  ${CUPS_BACKEND}" "cmd"
        if [ "${CUPS_BACKEND}" = "/usr/lib64/cups/backend" ];
        then
          if [ -d "/usr/lib/cups/backend" ];
          then
            if [ ! -x "/usr/lib/cups/backend/nx" ];
            then
              commandInstall "root" "${ROOTGNAME}" "755" "${NXSPOOL}" "/usr/lib/cups/backend/nx" "Cannot install nx cups backend in directory: /usr/lib/cups/backend" "cmd"
            fi
          fi
        fi
      fi

    else

      if [ -x "${CUPS_BACKEND}/nxprint" ];
      then
        SHOWCUPSINFO="no"
      else

        ${SEDCOMMAND} -e 's:NXROOT="":NXROOT="'"${NX_ROOT}"'":g'  "${NXPRINT}" > "${NXPRINT}".tmp
        commandRestoreFile "${NXPRINT}" "tmp"

        commandInstall "root" "${ROOTGNAME}" "500" "${NXPRINT}" "${CUPS_BACKEND}/nxprint" "Cannot install nxprint cups backend in directory: ${CUPS_BACKEND}" "cmd"

        setSELinuxContext "bin_t" "${CUPS_BACKEND}/nxprint"

        if [ "${CUPS_BACKEND}" = "/usr/lib64/cups/backend" ];
        then
          if [ -d "/usr/lib/cups/backend" ];
          then
            if [ ! -x "/usr/lib/cups/backend/nxprint" ];
            then
              commandInstall "root" "${ROOTGNAME}" "500" "${NXPRINT}" "/usr/lib/cups/backend/nxprint" "Cannot install nxprint cups backend in directory: /usr/lib/cups/backend" "cmd"
            fi
          fi
        fi
      fi
    fi
  fi
}


getLicenseAcronym ()
{
  license_file="$1"

  ret_getLicenseAcronym=""

  default_lic=1 
  if [ "x${license_file}" != "x" ];
  then
    default_lic=0
  fi

  if [ "x${LICENSE_ACRONYM}" != "x" ] && [ ${default_lic} = 1 ];
  then
   # When already set for default license
   return 0
  fi

  if [ "x${license_file}" = "x" ];
  then

    if [ "x${LICENSE_FILE}" != "x" ];
    then

      if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
      then
        license_file="${NX_ROOT}/etc/node.lic"
      else
        license_file="${LICENSE_FILE}"
      fi

    else
      if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
      then
        license_file="${NX_ROOT}/etc/node.lic"
      else
        license_file="${NX_ROOT}/etc/server.lic"
      fi

    fi
  fi

  if [ -f "${license_file}" ];
  then
    file_lic="${license_file}"
  elif [ -f "${license_file}.sample" ];
  then
    file_lic="${license_file}.sample"
  else
    printMsg "Cannot find license file to read an acronym" "warn"
    return 0
  fi

  ret_getLicenseAcronym=`${AWKCOMMAND} '/^Product Id/ {print $3}' "${file_lic}"`

  if [ "x${ret_getLicenseAcronym}" = "x" ];
  then
    printMsg "Error while reading an acronym from license file: ${file_lic}" "warn"
    return 0
  fi

  if [ ${default_lic} = 1 ];
  then
    # set global LICENSE_ACRONYM variable only in case of reading default license file
    LICENSE_ACRONYM=${ret_getLicenseAcronym}
  fi
}

isEvalPackage ()
{
  lic_acronym="$1"

  ret_isEvalPackage=0

  if [ "x${lic_acronym}" = "x" ];
  then
    getLicenseAcronym
    lic_acronym="${LICENSE_ACRONYM}"
  fi

  if [[ ${lic_acronym} =~ E$ ]];
  then
    ret_isEvalPackage=1
  fi
}

getLicenseSubscription ()
{
  license_file="$1"

  ret_getLicenseSubscription=""

  if [ "x${license_file}" = "x" ];
  then
    license_file="${LICENSE_FILE}"
  fi

  tmp=`${AWKCOMMAND}  '/^Subscription Type/ {print $3}' "${lic_file}" 2>/dev/null`
  if [ "x${tmp}" != "x" ];
  then
   ret_getLicenseSubscription=${tmp}
  fi

  if [ "x${ret_getLicenseSubscription}" != "xEvaluation" ];
  then
    if [ "x${ret_getLicenseSubscription}" = "xNone" ];
    then
      ret_getLicenseSubscription="Evaluation"
    else
      isEvalPackage
      if [ ${ret_isEvalPackage} = 1 ];
      then
        ret_getLicenseSubscription="Evaluation"
      fi
    fi
  fi
}

comparePackages ()
{
  acronym_1="${1%?}"
  acronym_2="${2%?}"

  ret_comparePackages=1

  printMsg "comparePackages: $acronym_1 and $acronym_2" "cmd"

  if [ "x${acronym_1}" = "x${acronym_2}" ];
  then
    printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"
    ret_comparePackages=0
  fi
}

isInstalledHtd ()
{
  if [ "x${INSTALL_HTD}" = "x" ];
  then

    INSTALL_HTD=0

    if [ -f "${NX_ROOT}/bin/nxhtd.bin" ];
    then

      if [ -f "${WEBPLAYER_USR_CONFIG_FILE}" ] || [ -f "${WEBPLAYER_USR_CONFIG_FILE}".sample ] || [ -f "${WEBPLAYER_USR_CONFIG_FILE}".backup ];
      then
        INSTALL_HTD=1
      fi

    fi
  fi
}


isEnabledHtd ()
{
  ret_isEnabledHtd=0

  if [ -f "${CONFIG_FILE}" ];
  then
    getValueFromCfgFile "${ENABLE_HTTP_CFG_KEY}" "${SERVER_USR_CONFIG_FILE}"
  else
    getValueFromCfgFile "${ENABLE_HTTP_CFG_KEY}" "${SERVER_USR_CONFIG_FILE}.backup"
  fi

  if [ ${ret_getValueFromCfgFile} = 2 ];
  then
    if [ "x${cfg_val}" = "xAutomatic" ] || [ ${cfg_val} = 1 ];
    then
      ret_isEnabledHtd=1
      return 0
    fi
  elif [ ${ret_getValueFromCfgFile} = 1 ];
  then
    ret_isEnabledHtd=1
    return 0
  fi
}

isSupportedHtd ()
{
  ret_isSupportedHtd=0

  isInstalledHtd
  if [ "x${INSTALL_HTD}" != "x1" ]
  then
    ret_isSupportedHtd=0
    return 0
  fi

  getLicenseAcronym

  if [ "x${LICENSE_ACRONYM}" = "x" ];
  then
    printMsg "Cannot read license acronym" "warn"
    return 0
  fi

  if [ "x${LICENSE_ACRONYM:1:2}" = "xCS" ] || [ "x${LICENSE_ACRONYM:1:2}" = "xQS" ] || \
     [ "x${LICENSE_ACRONYM:1:2}" = "xPS" ];
  then
    INSTALL_HTD=1
    ret_isSupportedHtd=1
    return 0
  else
    INSTALL_HTD=0
    ret_isSupportedHtd=0
    return 0
  fi

}

getHtdPortFromConfigFile ()
{

  ret_isSupportedHtd=""

  ret_getNxHtdPort=""
  ret_getNxHtdsPort=""

  isSupportedHtd
  if [ "x${ret_isSupportedHtd}" != "x1" ];
  then
    return 0
  fi

  isEnabledHtd 
  if [ "x${ret_isEnabledHtd}" = "x1" ];
  then
    getUsrConfigFile "htd"
    htdConfigFile="${ret_getUsrConfigFile}"
    if [ -f "${htdConfigFile}" ];
    then
      out=`${GREPCOMMAND} "^ *Listen " ${htdConfigFile} | ${SEDCOMMAND}  's/Listen *[0-9.]*://g'`
      ret_getNxHtdPort=`${ECHOCOMMAND} ${out} | ${CUTCOMMAND} -d ' ' -f 1`
      ret_getNxHtdsPort=`${ECHOCOMMAND} ${out} | ${CUTCOMMAND} -d ' ' -f 2`

      if [ "x${ret_getNxHtdPort}" = "x${ret_getNxHtdsPort}" ];
      then
        ret_getNxHtdsPort=""
      fi
    fi
  fi
}

getUserHomeDir ()
{
  ret_getUserHomeDir=`${AWKCOMMAND} -F ':' -v user="$1" '{if ($1==user) {print $6}}' /etc/passwd 2>/dev/null`

  return 0
}

checkGroupExist ()
{
  ret_checkGroupExist=`${GREPCOMMAND} "^$1:" /etc/group 2>/dev/null`

  return 0
}

getGroupById ()
{
  ret_getGroupById=""

  if [ "x${system}" = "xmacosx" ];
  then
    return 0

  else
    ret_getGroupById=`${CATCOMMAND} /etc/group 2>/dev/null | ${AWKCOMMAND} -F ":" '{if ($3==0) {print $1}}'`
  fi
}

addUserLinux ()
{
  user="$1"
  CREATE_HOME_DIR="$2"
 
  checkGroupExist "${user}"

  if [ "x${ret_checkGroupExist}" = "x" ];
  then
    runCommand "${GROUPADDCOMMAND} ${user}" "Cannot add group: ${user} to the system" "error"
  fi

  if [ "x${system}" != "xdebian" ]
  then

    sysuser=`${USERADDCOMMAND} --help 2>&1|${GREPCOMMAND} "\-r"`;
    if [ "x${sysuser}" != "x" ]
    then
      sysuser="-r"
    else
      sysuser=""
    fi

    if [ "x${CREATE_HOME_DIR}" = "x1" ];
    then
       commandMkDir "${NXUSERHOME}/${user}"
       home_dir=""
    else
       home_dir="-M"
    fi

    add_secondary_group="" 
    if [ "x${SECONDARY_GROUP}" != "x" ];
    then
      add_secondary_group="-G ${SECONDARY_GROUP}" 
    fi

    if [ "x${system}" = "xmandriva" -o "x${system}" = "xfedora" ];
    then
      runCommand "${USERADDCOMMAND} -d '${NXUSERHOME}/${user}' -p '*' -g ${user} ${add_secondary_group} -s /bin/false ${sysuser} ${home_dir} ${user}" "Cannot add user: ${user} to the system" "error"
    else
      runCommand "${USERADDCOMMAND} -d '${NXUSERHOME}/${user}' -p '*' -g ${user} ${add_secondary_group} -s /bin/false ${sysuser} ${user}" "Cannot add user: ${user} to the system" "error"
    fi
  else
    runCommand "${ADDUSERCOMMAND}  --home '${NXUSERHOME}/${user}' --system --disabled-password --ingroup ${user} --shell /bin/false ${user}" "Cannot add user: ${user} to the system" "error"
    runCommand "${USERMODCOMMAND} -p '*' ${user} " "Cannot unlock user: ${user}" "error"

    if [ "x${SECONDARY_GROUP}" != "x" ];
    then
      runCommand "${USERMODCOMMAND} -G '${SECONDARY_GROUP}' ${USER_NX}" "Cannot add user ${USER_NX} to secondary group ${SECONDARY_GROUP}" "warn"
    fi

  fi

  if [ -f /etc/nscd.conf ]
  then
    tmp=`$NSCDCOMMAND --invalidate passwd 2>&1`
    if [ "x${tmp}" != "x" ];
    then
      printMsg "nscd output: $tmp" "cmd"
    fi
  else
    result=`${IDCOMMAND} ${user} 2>&1`
    if [ $? = 0 ];
    then
      $SLEEPCOMMAND 2
    fi
  fi

}

getProcessPID ()
{
  tab_PID=`${PSCOMMAND} ax -o "pid,command" 2>/dev/null | ${GREPCOMMAND} "$1" | ${GREPCOMMAND} -v uninstall | ${GREPCOMMAND} -v grep | ${AWKCOMMAND} '{print $1;}' 2>/dev/null`
}

killNXApp ()
{
  nxapp="$1"

  if [ "x${nxapp}" = "x" ];
  then
    return
  fi
        
  getProcessPID "${NX_ROOT}/bin/${nxapp}"

  for i in ${tab_PID}; do
    printMsg "Killing process: ${nxapp} ($i)" "cmd"
    commandKill "$i"
  done

  if [ "x${system}" = "xmacosx" ];
  then
    getProcessPID "MacOS/${nxapp}"

    for i in ${tab_PID}; do
      printMsg "Killing process: ${nxapp} ($i)" "cmd"
      commandKill "$i"
    done
  fi
}

killNXApplications ()
{
  for ((j=0;j<${#processes_to_kill[@]};j++)); do
    killNXApp "${processes_to_kill[${j}]}"
  done
}

getModefromConfigFile ()
{
  ret_getModefromConfigFile=""

  config_file="${SERVER_USR_CONFIG_FILE}"

  if [ ! -f "${config_file}" ];
  then
    if [ -f "${config_file}.backup" ];
    then
      config_file="${config_file}.backup"
    else
      printMsg "Cannot read current installation type from config file. File ${config_file} not found" "warn"

      ret_getModefromConfigFile=""
      return 0
    fi
  fi

  getValueFromCfgFile "InstallationType" "${config_file}"
  if [ ${ret_getValueFromCfgFile} = 2 ];
  then
    ret_getModefromConfigFile="${cfg_val}"
  fi

}

setModeinConfigFile ()
{
  mode="$1"

  ret_setModeinConfigFile=0

  config_file="${SERVER_USR_CONFIG_FILE}"

  if [ ! -f "${config_file}" ];
  then
    if [ -f "${config_file}.backup" ];
    then
      config_file="${config_file}.backup"
    else
      printMsg "Cannot set current installation type in config file. File ${config_file} not found" "warn"

      ret_setModeinConfigFile=1
      return 0
    fi
  fi

  setValueAtCfgFile "${config_file}" "InstallationType" "${mode}"
}

whichPath ()
{
  which_out=""
  if [ "x$1" != "x" ];
  then
    which_out=`${WHICHCOMMAND} $1 2>/dev/null | ${HEADCOMMAND} -1 | ${GREPCOMMAND} -v "no $1 in"`
  fi
}

pathBin=(/usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin)

findPath ()
{
  tool_name="$1"

  ret_findPath=""

  for i in ${pathBin[@]}; do
    if [ -x "$i/${tool_name}" ];
    then
      ret_findPath="$i/${tool_name}"
      return 0
    fi
  done
}

getToolPath ()
{
  tool_name="$1"

  ret_getToolPath=""

  if [ "x${tool_name}" = "x" ];
  then
    return 0
  fi

  whichPath "${tool_name}"
  if [ "x${which_out}" != "x" ];
  then
    ret_getToolPath="${which_out}"
    return 0
  fi

  findPath "${tool_name}"
  if [ "x${ret_findPath}" != "x" ];
  then
    ret_getToolPath="${ret_findPath}"
    return 0
  fi
}

setToolPathInCfg ()
{
  tool_name="$1"
  key_name="$2"
  update="$3"

  if [ "x${tool_name}" = "x" ];
  then
    return 0
  fi

  getValueFromCfgFile "${tool_name}" "${CONFIG_FILE}"
  if [ ${ret_getValueFromCfgFile} = 2 ] && [ "x${update}" != "x1" ];
  then
    printMsg "Path for tool: ${tool_name} is already set to ${cfg_val}" "cmd"
    return 0
  fi

  getToolPath "${tool_name}"   
  if [ "x${ret_getToolPath}" != "x" ];
  then
    setValueAtCfgFile "${CONFIG_FILE}" "${key_name}" "${ret_getToolPath}"
    printMsg "Updated key: ${key_name}=${ret_getToolPath}" "cmd"
  fi
}

finalRemoveLeftoversPkg ()
{
  commandRmDirRecursively "/etc/NX"
}

removeVARDir ()
{
  commandRmDirRecursively "${NX_VAR_DIR}/db"
  commandRmDirRecursively "${NX_VAR_DIR}/run"
  commandRmDirRecursively "${NX_VAR_DIR}/tmp"

  commandRmIfExist "${NX_VAR_DIR}/num"

  #removing log, except nxuninstall.log file 
  commandRmDirRecursively "${NX_VAR_DIR}/log/nxnode"
  commandRmDirRecursively "${NX_VAR_DIR}/log/nxserver"
  commandRmIfExist "${NX_VAR_DIR}/log/nxd.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxd.pid"
  commandRmIfExist "${NX_VAR_DIR}/log/nxerror.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxhtd-access.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxhtd-error.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxinstall.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxupdate.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxserver.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxwebclient.log"

  #old log files
  commandRmIfExist "${NX_VAR_DIR}/log/install"
  commandRmIfExist "${NX_VAR_DIR}/log/uninstall"
  commandRmIfExist "${NX_VAR_DIR}/log/update"
}

getPAMPath ()
{
  ret_getPAMPath=""

  if [ -d /etc/pam.d ];
  then
    ret_getPAMPath="/etc/pam.d"
  elif [ -d /etc/security/pam.d ];
  then
    ret_getPAMPath="/etc/security/pam.d"
  fi
}

installPAMScript ()
{
  pamScriptPath="$1" 

  if [ "x${system}" = "xmacosx" ];
  then
    getMacOSXVersion

    if [ "x${mac_ver_major}.${mac_ver_minor}" = "x10.5" ];
    then
      if [ -f "${pamScriptPath}-10.5" ];
      then
        if [ -f "${pamScriptPath}" ];
        then 
          commandMv "${pamScriptPath}" "${pamScriptPath}.new"
        fi

        commandCp "${pamScriptPath}-10.5" "${pamScriptPath}"
      fi
    fi
  fi

  if [ "x${system}" = "xredhat" ];
  then
    getDistroVersion

    majorDstrVer=$(echo "$ret_DistroVersion" | cut -d '.' -f 1)

    if [ $majorDstrVer -eq 4 ];
    then
      if [ -f "${pamScriptPath}-legacy" ];
      then
        if [ -f "${pamScriptPath}" ];
        then 
          commandMv "${pamScriptPath}" "${pamScriptPath}.new"
        fi

        commandCp "${pamScriptPath}-legacy" "${pamScriptPath}"
      fi
    elif [ $majorDstrVer -ge 6 ] && \
         ( [ -f "/lib64/security/pam_loginuid.so" ] || \
           [ -f "/lib/security/pam_loginuid.so" ] );
    then
      if [ -f "${pamScriptPath}-login" ];
      then
        if [ -f "${pamScriptPath}" ];
        then 
          commandMv "${pamScriptPath}" "${pamScriptPath}.new"
        fi

        commandCp "${pamScriptPath}-login" "${pamScriptPath}"
      fi
    fi
  fi

  if [ -f "${pamScriptPath}" ];
  then
    getPAMPath

    if [ -d "${ret_getPAMPath}" ];
    then
      commandInstall "root" "${ROOTGNAME}" "644" "${pamScriptPath}" "${ret_getPAMPath}/" "Cannot install PAM script: ${pamScriptPath}"
    else
      printMsg "Cannot install PAM script: ${pamScriptPath}. PAM directory not found" "cmd"
    fi
     
  else
    printMsg "Cannot install PAM script: ${pamScriptPath}. File not found" "cmd"
  fi
}

removePAMScript ()
{
  pamScriptName="$1"

  getPAMPath

  if [ -d "${ret_getPAMPath}" ];
  then
    commandRm "${ret_getPAMPath}/${pamScriptName}" "Cannot uninstall PAM script: ${pamScriptName}"
  else
    printMsg "Cannot uninstall PAM script: ${pamScriptName}. PAM directory not found" "cmd"
  fi
}

installnxPAMScript ()
{
  if [ "x${system}" != "xmacosx" ];
  then
    if [ ! -f /etc/default/locale ];
    then
      $SEDCOMMAND -e 's/\( *session.*etc.default.locale.*\)/#\1/' "${NX_PAM_SCRIPT}" > "${NX_PAM_SCRIPT}.tmp"
      commandRestoreFile "${NX_PAM_SCRIPT}" "tmp"
    fi
  fi

  installPAMScript "${NX_PAM_SCRIPT}"
}

installnxlimitsPAMScript ()
{
  installPAMScript "${NX_PAM_SCRIPT_LIMITS}"
}

checkRequiredPAMWheel ()
{
  line_wheel="$1"

  #"auth required pam_wheel"

  if [ "x${REQUIRED_PAM_WHEEL}" = "x1" ];
  then
    # alredy set
    return 0
  fi

  if [[ "${line_wheel}" =~ ^[[:space:]]*auth[[:space:]]*required[[:space:]]*.*[[:space:]]*pam_wheel ]];
  then
    #printMsg "Found REQUIRED_PAM_WHEEL in line: $line_wheel" "cmd"
    REQUIRED_PAM_WHEEL=1
#  elif [[ "${line_wheel}" =~ ^[[:space:]]*auth[[:space:]]*pam_wheel.*trust ]];
#  then
#    printMsg "Found REQUIRED_PAM_WHEEL (trust) in line: $line_wheel" "cmd"
#    REQUIRED_PAM_WHEEL=1
  fi

}

checkSufficientPAMWheel ()
{
  line_wheel="$1"

  #auth sufficient pam_wheel

  if [ "x${SUFFICIENT_PAM_WHEEL}" = "x1" ];
  then
    # alredy set
    return 0
  fi

  if [[ "${line_wheel}" =~ ^[[:space:]]*auth[[:space:]]*sufficient[[:space:]]*.*[[:space:]]*pam_wheel ]];
  then
    #printMsg "Found SUFFICIENT_PAM_WHEEL in line: $line_wheel" "cmd"
    SUFFICIENT_PAM_WHEEL=1
  fi

}

addPAMFileToArray ()
{
  filename="$1"

  if [ "x$filename" = "x" ];
  then
    #empty file name
    return 0
  fi

  file_exist=0
  for i in ${INCLUDE_PAM_FILES[@]}
  do
    #printMsg "Reading file: $i" "cmd"
    if [ "x${filename}" = "x$i" ];
    then
      file_exist=1
    fi
  done

  if [ "x${file_exist}" != "x1" ];
  then
    INCLUDE_PAM_FILES[$INCLUDE_PAM_FILES_COUNT]="$filename"
    INCLUDE_PAM_FILES_COUNT=`expr ${INCLUDE_PAM_FILES_COUNT} + 1`
  fi
}

getIncludeFile ()
{
  line_wheel="$1"

  if [[ "${line_wheel}" =~ ^[[:space:]]*@include ]];
  then
    INCLUDE_PAM_FILE=`${ECHOCOMMAND} $line_wheel | ${AWKCOMMAND} '{print $2}'`
    #printMsg "Found INCLUDE_PAM_FILE: $INCLUDE_PAM_FILE" "cmd"
    addPAMFileToArray "${INCLUDE_PAM_FILE}"
  elif [[ "${line_wheel}" =~ ^[[:space:]]*auth[[:space:]]*include ]];
  then
    INCLUDE_PAM_FILE=`${ECHOCOMMAND} $line_wheel | ${AWKCOMMAND} '{print $3}'`
    #printMsg "Found INCLUDE_PAM_FILE: $INCLUDE_PAM_FILE" "cmd"
    addPAMFileToArray "${INCLUDE_PAM_FILE}"
  elif [[ "${line_wheel}" =~ service= ]];
  then
    INCLUDE_PAM_FILE=`${ECHOCOMMAND} $line_wheel | ${AWKCOMMAND} -F "service=" '{print $2}' | ${AWKCOMMAND} '{print $1}'`
    #printMsg "Found INCLUDE_PAM_FILE: $INCLUDE_PAM_FILE" "cmd"
    addPAMFileToArray "${INCLUDE_PAM_FILE}"
  fi

}

checkPAMLine ()
{
  pamLine=$1

  checkRequiredPAMWheel "${pamLine}"

  checkSufficientPAMWheel "${pamLine}"

  getIncludeFile "${pamLine}"

}


readPAMFile ()
{
  pamFile=$1

  #printMsg "Parsing PAM file: ${pamFile}" "cmd"

  while read line
  do

    if [[ "$line" =~ ^[[:space:]]*$ ]];
    then

      $ECHOCOMMAND "Skipping empty line: $line" > /dev/null

    elif [[ ! "$line" =~ ^[[:space:]]*# ]];
    then

      checkPAMLine "$line"

    fi

  done <${pamFile}
}


parsePAMFile ()
{
  getPAMPath
  NX_PAM_DIR="${ret_getPAMPath}"

  NX_PAM_FILE=${NX_PAM_DIR}/nx

  REQUIRED_PAM_WHEEL=0
  SUFFICIENT_PAM_WHEEL=0
  INCLUDE_PAM_FILES=()
  INCLUDE_PAM_FILES_COUNT=0

  if [ ! -f "${NX_PAM_FILE}" ];
  then
    printMsg "parsePAMFile: file does not exist: ${NX_PAM_FILE}" "cmd"
    return 0
  fi

  readPAMFile "${NX_PAM_FILE}"

  ################################
  #Level 1

  files_count=$INCLUDE_PAM_FILES_COUNT
  files_array=("${INCLUDE_PAM_FILES[@]}")

  INCLUDE_PAM_FILES_COUNT=0
  INCLUDE_PAM_FILES=()

  for i in ${files_array[@]}
  do
    readPAMFile "${NX_PAM_DIR}/${i}"
  done

  ################################
  #Level 2

  files_count=$INCLUDE_PAM_FILES_COUNT
  files_array=("${INCLUDE_PAM_FILES[@]}")

  INCLUDE_PAM_FILES_COUNT=0
  INCLUDE_PAM_FILES=()

  for i in ${files_array[@]}
  do
    readPAMFile "${NX_PAM_DIR}/${i}"
  done
}

getPreviousVersion ()
{
  major_version=0
  minor_version=0
  maintenance_version=0

  previous_version=""

  if [ -f "${NX_ROOT}/etc/version.backup" ];
  then
    previous_version=$("${CATCOMMAND}" "${NX_ROOT}/etc/version.backup")
  elif [ -f "${NX_ROOT}/etc/version.temporary" ];
  then
    previous_version=$("${CATCOMMAND}" "${NX_ROOT}/etc/version.temporary")
  fi

  if [ "${previous_version}x" != "x" ]
  then

    major_version=$("$ECHOCOMMAND" "${previous_version}" | "$CUTCOMMAND" -d '.' -f1)

    minor_version=$("$ECHOCOMMAND" "${previous_version}" | "$CUTCOMMAND" -d '.' -f2)

    maintenance_version=$("$ECHOCOMMAND" "${previous_version}" | "$CUTCOMMAND" -d '.' -f3)
  fi
}

rmPreviousVersion ()
{
  if [ -f "${NX_ROOT}/etc/version.backup" ];
  then
    commandRm "${NX_ROOT}/etc/version.backup" "cmd"
  fi
}

installIncreaseVersionPackage()
{
  checkRPM="1"

  getToolPath dpkg

  if [ "x${ret_getToolPath}" != "x" ];
  then

    DPKGCOMMAND="${ret_getToolPath}"

    printMsg "Found dpkg path: ${DPKGCOMMAND}" "cmd"

    runCommand "PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin '${DPKGCOMMAND}' --get-selections | '${GREPCOMMAND}' nomachine" "Cannot query deb packages" "cmd"

    if [ "x${ret_runCommand}" = "x0" ];
    then

      printMsg "Installation of nomachine_automatic_update.deb" "cmd"

      checkRPM="0"

      runCommand "PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin '${DPKGCOMMAND}' -i '${NX_ROOT}'/nomachine_automatic_update.deb" "Cannot install nomachine_automatic_update.deb" "cmd"

    fi
  fi

  if [ "x${checkRPM}" = "x1" ]; then

    getToolPath rpm

    if [ "x${ret_getToolPath}" != "x" ];
    then

      printMsg "Found rpm path: ${RPMCOMMAND}" "cmd"

      RPMCOMMAND="${ret_getToolPath}"

      runCommand "'${RPMCOMMAND}' -qa | '${GREPCOMMAND}' nomachine" "Cannot query rpm packages" "cmd"

      if [ "x${ret_runCommand}" = "x0" ];
      then

        printMsg "Installation of nomachine_automatic_update.rpm" "cmd"

        runCommand "'${RPMCOMMAND}' -U '${NX_ROOT}'/nomachine_automatic_update.rpm" "Cannot install nomachine_automatic_update.rpm" "cmd"

      fi
    fi
  fi

  commandRm "${NX_ROOT}/nomachine_automatic_update.rpm" "warn"

  commandRm "${NX_ROOT}/nomachine_automatic_update.deb" "warn"
}

isAnywhereAvailable ()
{
  if [ -f "${NX_ROOT}/etc/anywhere.cfg" ] || [ -f "${NX_ROOT}/etc/network.cfg" ];
  then
    anywhere="1"
  else
    anywhere="0"
  fi
}



NXFSSCRIPT="$NX_ROOT/scripts/restricted/nxfs.sh"
NXUSBSCRIPT="$NX_ROOT/scripts/restricted/nxusb.sh"
NXTUNSCRIPT="$NX_ROOT/scripts/restricted/nxtun.sh"
NXTUNFINDSCRIPT="$NX_ROOT/scripts/nxtunfind.sh"

NXTUNDESTDIR="/Library/Application Support/NoMachine/Extensions"
NXTUNSTARTDIR="/System/Library/StartupItems/"

NXDISKDIR="$NX_ROOT/bin/drivers"
NXDISKDESTDIR="/Library/Application Support/NoMachine/Extensions"
NXDISKSTARTDIR="/System/Library/StartupItems"

#NXPAMDSCRIPTSRC="${NX_ROOT}/scripts/etc/pam.d/nxsshd"
#NXPAMDSCRIPTDST="/etc/pam.d/nxsshd"

NXUSBSTARTDIR="/Library/LaunchDaemons/"
NXUSBSTARTSRC="${NX_ROOT}/scripts/init/nxusb/com.nomachine.nxusb.plist"
NXUSBKEXTDIR="${NX_ROOT}/bin/drivers"

NXVACDESTDIR="/System/Library/Extensions/nxaudio.kext"

NXUSBKEXTDESTDIR="/Library/Application Support/NoMachine/Extensions"

if [ -a "/sbin/kextload" ];
then
  COMMANDKEXTLOAD="/sbin/kextload"
else
  COMMANDKEXTLOAD="kextload"
fi

if [ -a "/sbin/kextunload" ];
then
  COMMANDKEXTUNLOAD="/sbin/kextunload"
else
  COMMANDKEXTUNLOAD="kextunload"
fi

if [ -a "/sbin/kextstat" ];
then
  COMMANDKEXTSTAT="/sbin/kextstat"
elif [ -a "/usr/sbin/kextstat" ];
then
  COMMANDKEXTSTAT="/usr/sbin/kextstat"
elif [ -a "/usr/bin/kextstat" ];
then
  COMMANDKEXTSTAT="/usr/bin/kextstat"
elif [ -a "/bin/kextstat" ];
then
  COMMANDKEXTSTAT="/bin/kextstat"
else
  COMMANDKEXTSTAT="kextstat"
fi

setRestrictedPermissionsDevices ()
{
  if [ -f "${NXTUNSCRIPT}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXTUNSCRIPT}"
  else
    printMsg "No such file: ${NXTUNSCRIPT}" "warn"
  fi

  if [ "x${system}" = "xmacosx" ];
  then
    if [ -f "${NXFSSCRIPT}" ];
    then
      commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXFSSCRIPT}"
    else
      printMsg "No such file: ${NXFSSCRIPT}" "warn"
    fi

    if [ -f "${NXTUNFINDSCRIPT}" ];
    then
      commandChownChmod "root:${ROOTGNAME}" "755" "${NXTUNFINDSCRIPT}"
    else
      printMsg "No such file: ${NXTUNFINDSCRIPT}" "warn"
    fi
  fi
}


startNfsService ()
{
  if [ -f "${NODE_USR_CONFIG_FILE}" ];
  then
    getValueFromCfgFile "EnableFileTransfer" "${NODE_USR_CONFIG_FILE}"
    if [ "${ret_getValueFromCfgFile}" = "2" ];
    then
      if [ "${cfg_val}" = "none" ] || [ "${cfg_val}" = "client" ];
      then
        return 0
      fi
    fi
  fi

  runCommand "${COMMANDKEXTLOAD} ${NXDISKDESTDIR}/nxfs.kext" "Cannot load: nxfs"
}

installNfsService ()
{
  if [ "${system}" != "macosx" ];
  then
    return 0
  fi

  if [ -d "${NXDISKDESTDIR}/nxfs.kext" ];
  then
    commandRmDirRecursively "${NXDISKDESTDIR}/nxfs.kext" "cmd"
  fi

  if [ -d "/System/Library/Extensions/nxfs.kext" ];
  then
    commandRmDirRecursively "/System/Library/Extensions/nxfs.kext" "cmd"
  fi

  if [ -d "/Library/Extensions/nxfs.kext" ];
  then
    commandRmDirRecursively "/Library/Extensions/nxfs.kext" "cmd"
  fi

  if [ ! -d "${NXDISKDESTDIR}" ];
  then
    commandMkDir "${NXDISKDESTDIR}"
  fi

  commandCpDir "${NXDISKDIR}/nxfs.kext" "${NXDISKDESTDIR}"

  commandChownR "root:${ROOTGNAME}" "${NXDISKDESTDIR}/nxfs.kext"

  if [ -d "${NXDISKSTARTDIR}/nxfs" ];
  then
    commandRmDirRecursively "${NXDISKSTARTDIR}/nxfs" "cmd"
  fi
}

uninstallNfsService ()
{
  outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxfs 2>&1`

  if [ "${outCommand}x" != "x" ];
  then
    runCommand "${COMMANDKEXTUNLOAD} ${NXDISKDESTDIR}/nxfs.kext" "Cannot unload nxfs"
  fi

  outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxfs 2>&1`

  if [ "${outCommand}x" = "x" ];
  then
    commandRmDirRecursively "${NXDISKSTARTDIR}/nxfs" "cmd"
  else
    runCommand "${COMMANDKEXTUNLOAD} ${NXDISKDESTDIR}/nxfs.kext" "Cannot unload nxfs for second time"

    commandRmDirRecursively "${NXDISKSTARTDIR}/nxfs" "cmd"
  fi
}

installUsbService ()
{
  #
  # Removing old kext
  #

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb.kext" "cmd"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb_helper.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb_helper.kext" "cmd"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb_io1.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb_io1.kext" "cmd"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb_io2.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb_io2.kext" "cmd"
  fi

  if [ ! -d "${NXUSBKEXTDESTDIR}" ];
  then
    commandMkDir "${NXUSBKEXTDESTDIR}" "cmd"
  fi

  getMacOSXVersion

  if [ "x${mac_ver_minor}" != "x5" ];
  then
    commandCpDir "${NXUSBKEXTDIR}/nxusb.kext" "${NXUSBKEXTDESTDIR}"

    commandChmodR "755" "${NXUSBKEXTDESTDIR}/nxusb.kext"

    commandChownR "root:${ROOTGNAME}" "${NXUSBKEXTDESTDIR}/nxusb.kext"

    if [ -f "${NXUSBSTARTDIR}/com.nomachine.nxusb.plist" ];
    then
      commandRm "${NXUSBSTARTDIR}/com.nomachine.nxusb.plist" "cmd"
    fi

    ${SEDCOMMAND} -e 's:@NXROOT@:'"${NX_ROOT}"':g'  "${NXUSBSTARTSRC}" > "${NXUSBSTARTSRC}".tmp

    commandRestoreFile "${NXUSBSTARTSRC}" "tmp"

  fi
}

uninstallUsbService ()
{
  outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxusb 2>&1`

  if [ "${outCommand}x" != "x" ];
  then
    runCommand "${COMMANDKEXTUNLOAD} -b com.nomachine.driver.nxusb" "Cannot unload nxusb kext"
  fi

  outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxusb 2>&1`

  if [ "${outCommand}x" != "x" ];
  then
    runCommand "${COMMANDKEXTUNLOAD} -b com.nomachine.driver.nxusb" "Cannot unload nxusb kext for second time"
  fi

  runCommand "${LAUNCHCTLCOMMAND} unload ${NXUSBSTARTDIR}/com.nomachine.nxusb.plist" "Cannot unload nxusb plist file" "nolog"

  commandRm "${NXUSBSTARTDIR}/com.nomachine.nxusb.plist" "cmd" "Cannot remove nxusb"
}

installServices ()
{
  if [ "x${system}" = "xsolaris" ];
  then
    return 0
  fi

  if [ "${system}" = "macosx" ];
  then
    installNetworkInterface

    installNfsService

    installUsbService

    if [ "x${NX_MPKG_PACKAGE}" = "xplayer" ];
    then
      commandTouch "/System/Library/Extensions" "warn"
    fi

  fi
}


startNetworkInterface ()
{
  if [ -f "${NODE_USR_CONFIG_FILE}" ];
  then
    getValueFromCfgFile "EnableNetworkSharing" "${NODE_USR_CONFIG_FILE}"
    if [ "${ret_getValueFromCfgFile}" = "2" ];
    then
      if [ "${cfg_val}" = "none" ] || [ "${cfg_val}" = "client" ];
      then
        return 0
      fi
    fi
  fi

  runCommand "${NXTUNSTARTDIR}nxtun/nxtun start" "Cannot startup: nxtun"
}

installNetworkInterface ()
{
  if [ "${system}" = "macosx" ];
  then
    if [ -d "${NXTUNDESTDIR}/nxtun.kext" ];
    then
      commandRmDirRecursively "${NXTUNDESTDIR}/nxtun.kext" "cmd"
    fi

    if [ -d "/System/Library/Extensions/nxtun.kext" ];
    then
      commandRmDirRecursively "/System/Library/Extensions/nxtun.kext" "cmd"
    fi

    if [ -d "/Library/Extensions/nxtun.kext" ];
    then
      commandRmDirRecursively "/Library/Extensions/nxtun.kext" "cmd"
    fi

    if [ ! -d "${NXTUNDESTDIR}" ];
    then
      commandMkDir "${NXTUNDESTDIR}"
    fi

    commandCpDir "${NX_ROOT}/bin/drivers/nxtun.kext" "${NXTUNDESTDIR}"

    commandChownR "root:${ROOTGNAME}" "${NXTUNDESTDIR}/nxtun.kext"

    if [ -d "${NXTUNSTARTDIR}/nxtun" ];
    then
      commandRmDirRecursively "${NXTUNSTARTDIR}/nxtun" "cmd"
    fi
  fi
}

uninstallServices ()
{

  if [ "${system}" != "macosx" ];
  then
    return 0
  fi

  uninstallNetworkInterface
  uninstallUsbService
  uninstallNfsService

}

uninstallNetworkInterface ()
{

  if [ "${system}" = "macosx" ];
  then
    if [ -a "/sbin/kextunload" ];
    then
      COMMANDKEXTUNLOAD="/sbin/kextunload"
    else
      COMMANDKEXTUNLOAD="kextunload"
    fi

    if [ -a "/sbin/kextstat" ];
    then
      COMMANDKEXTSTAT="/sbin/kextstat"
    elif [ -a "/usr/sbin/kextstat" ];
    then
      COMMANDKEXTSTAT="/usr/sbin/kextstat"
    elif [ -a "/usr/bin/kextstat" ];
    then
      COMMANDKEXTSTAT="/usr/bin/kextstat"
    elif [ -a "/bin/kextstat" ];
    then
      COMMANDKEXTSTAT="/bin/kextstat"
    else
      COMMANDKEXTSTAT="kextstat"
    fi

    outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxtun 2>&1`

    if [ "${outCommand}x" != "x" ];
    then
      runCommand "${COMMANDKEXTUNLOAD} ${NXTUNDESTDIR}/nxtun.kext" "Cannot unload nxtun"
    fi

    outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxtun 2>&1`

    if [ "${outCommand}x" = "x" ];
    then
      commandRmDirRecursively "${NXTUNSTARTDIR}/nxtun" "cmd"
    else
      runCommand "${COMMANDKEXTUNLOAD} ${NXTUNDESTDIR}/nxtun.kext" "Cannot unload nxtun for second time"

      commandRmDirRecursively "${NXTUNDESTDIR}/nxtun.kext" "cmd"

      commandRmDirRecursively "${NXTUNSTARTDIR}/nxtun" "cmd"
    fi
  fi

}

uninstallNXAudio ()
{
  if [ -a "/sbin/kextunload" ];
  then
    COMMANDKEXTUNLOAD="/sbin/kextunload"
  else
    COMMANDKEXTUNLOAD="kextunload"
  fi

  if [ -a "/sbin/kextstat" ];
  then
    COMMANDKEXTSTAT="/sbin/kextstat"
  elif [ -a "/usr/sbin/kextstat" ];
  then
    COMMANDKEXTSTAT="/usr/sbin/kextstat"
  elif [ -a "/usr/bin/kextstat" ];
  then
    COMMANDKEXTSTAT="/usr/bin/kextstat"
  elif [ -a "/bin/kextstat" ];
  then
    COMMANDKEXTSTAT="/bin/kextstat"
  else
    COMMANDKEXTSTAT="kextstat"
  fi

  outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxaudio 2>&1`

  if [ "${outCommand}x" != "x" ];
  then
    runCommand "${COMMANDKEXTUNLOAD} ${NXVACDESTDIR}" "Cannot unload nxaudio"
  fi

  outCommand=`${COMMANDKEXTSTAT} | ${GREPCOMMAND} nxaudio 2>&1`

  if [ "${outCommand}x" != "x" ];
  then 
    runCommand "${COMMANDKEXTUNLOAD} ${NXVACDESTDIR}" "Cannot unload nxaudio for second time"
  fi
}

removeAllKexts ()
{
  if [ -d "${NXDISKDESTDIR}/nxfs.kext" ];
  then
    commandRmDirRecursively "${NXDISKDESTDIR}/nxfs.kext" "cmd"
  fi

  if [ -d "${NXTUNDESTDIR}/nxtun.kext" ];
  then
    commandRmDirRecursively "${NXTUNDESTDIR}/nxtun.kext" "cmd"
  fi

  if [ -d "${NXVACDESTDIR}" ];
  then
    commandRmDirRecursively "${NXVACDESTDIR}" "cmd"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb_helper.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb_helper.kext" "cmd" "Cannot remove nxusb helper"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb_io1.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb_io1.kext" "cmd" "Cannot remove nxusb io1"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb_io2.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb_io2.kext" "cmd" "Cannot remove nxusb io2"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}/nxusb.kext" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}/nxusb.kext" "cmd" "Cannot remove nxusb io2"
  fi

  if [ -d "/System/Library/Extensions/nxtun.kext" ];
  then
    commandRmDirRecursively "/System/Library/nxtun.kext" "cmd" "Cannot remove nxtun kext"
  fi

  if [ -d "/System/Library/Extensions/nxfs.kext" ];
  then
    commandRmDirRecursively "/System/Library/nxfs.kext" "cmd" "Cannot remove nxfs kext"
  fi

  if [ -d "/System/Library/Extensions/nxaudio.kext" ];
  then
    commandRmDirRecursively "/System/Library/nxaudio.kext" "cmd" "Cannot remove nxaudio kext"
  fi

  if [ -d "/Library/Extensions/nxtun.kext" ];
  then
    commandRmDirRecursively "/Library/nxtun.kext" "cmd" "Cannot remove nxtun kext"
  fi

  if [ -d "/Library/Extensions/nxfs.kext" ];
  then
    commandRmDirRecursively "/Library/nxfs.kext" "cmd" "Cannot remove nxfs kext"
  fi

  if [ -d "/Library/Extensions/nxaudio.kext" ];
  then
    commandRmDirRecursively "/Library/nxaudio.kext" "cmd" "Cannot remove nxaudio kext"
  fi

  if [ -d "${NXUSBKEXTDESTDIR}" ];
  then
    commandRmDirRecursively "${NXUSBKEXTDESTDIR}" "cmd" "Cannot remove Extensions dir"
  fi
}

#installPAM ()
#{
#  if [ -f "${NXPAMDSCRIPTSRC}" ];
#  then
#    commandCp "${NXPAMDSCRIPTSRC}" "${NXPAMDSCRIPTDST}" "warn"
#    commandChownChmod "root:${ROOTGNAME}" "444" "${NXPAMDSCRIPTDST}" "warn" 
#  fi
#}

uninstallPAM ()
{
  if [ -f "${NXPAMDSCRIPTDST}" ];
  then
    commandRm "${NXPAMDSCRIPTDST}" "warn"
  fi

}

startDevices ()
{
  setRestrictedPermissionsDevices
  setNxuexecPermisions

  nxPrintSetup

  startNetworkInterface
  startNfsService

  #installServices
  #installPAM
}

installDevices ()
{
  setRestrictedPermissionsDevices
  setNxuexecPermisions

  nxPrintSetup
  #installNetworkInterface
  installServices
  #installPAM
}

uninstallDevices ()
{
  removePrintSetup
  uninstallServices
  #uninstallNetworkInterface
  uninstallPAM
  if [ "x${system}" = "xmacosx" ];
  then
    uninstallNXAudio
    removeAllKexts
  fi
}





USBKERNELDIR="${NX_ROOT}/share/src/nxusb"
USBERRORFILE="${USBKERNELDIR}/.errorUsbModule"

XDG_MIME_FILE="${NX_XDG}/NoMachine-mime.xml"

NX_MEDIA="/media/nomachine"

selinux_execstack_files=(
/bin/nxclient.bin
/bin/nxauth
/bin/nxfs
/bin/nxkb
/bin/nxkeygen
/bin/nxsh
/bin/nxexec
/bin/nxfsm
)

setContextForLibraries()
{
  setSELinuxStatus

  if [ "${SELINUX_ENABLED}" = "1" ];
  then
    setSELinuxContextR "textrel_shlib_t" "${NX_ROOT}/lib/"
  fi

}

selinuxOperations()
{
  setSELinuxStatus

  if [ "${SELINUX_ENABLED}" = "1" ];
  then
    setContextForLibraries
    setSELinuxExecStack
  fi
}

fixTempXDir__solaris ()
{
  for files in "${WRAPPER}"
  do 
    if [ -f "${files}" ];
    then
      commandChownChmodSuid "root:root" "555" "${files}" "error"
    else 
      printMsg "No such file: ${files}" "error"

      exit 1
    fi
  done
}

installUsb ()
{
  create_usb_dir_tree

  if [ "x${system}" = "xmacosx" ] || [ "x${system}" = "xsolaris" ];
  then
    return 0
  fi

  printMsg "Compiling the USB module" 

  compile_usb_module
}

uninstallUsb ()
{
  if [ "x${system}" = "xmacosx" ] || [ "x${system}" = "xsolaris" ];
  then
    return 0
  fi

  printMsg "Stopping USB daemon" "cmd"

  stop_usb_daemon

  if [ "$ret_stop_usb_daemon" != 0 ];
  then
    printMsg "$cmdout" "cmd"
    printMsg "Stopping daemon failed" "cmd"
  else
    printMsg "Result: OK" "cmd"
  fi

  printMsg "Cleaning USB module" "cmd"

  clean_usb_module

  if [ "$ret_clean_usb_module" != 0 ];
  then
    printMsg "$cmdout" "cmd"
    printMsg "Cleaning module failed" "cmd"
  fi
}

updateUsb ()
{
  if [ "x${system}" = "xmacosx" ] || [ "x${system}" = "xsolaris" ];
  then
    return 0
  fi

  NEW_MODULE_VERSION=`"${SEDCOMMAND}" -n 's/.*MODULE_VERSION("\(.*\)").*/\1/p' "${USBKERNELDIR}/module.c"`

  OLD_MODULE_VERSION=""

  if [ -e "${NX_ROOT}/bin/drivers/nxusb.ko" ];
  then
    OLD_MODULE_VERSION=`${MODINFOCOMMAND} -F version "${NX_ROOT}/bin/drivers/nxusb.ko"`
  fi

  if [ "x${NEW_MODULE_VERSION}" != "x${OLD_MODULE_VERSION}" ];
  then

    printMsg "Stopping USB daemon" "cmd"

    stop_usb_daemon

    if [ "$ret_stop_usb_daemon" != 0 ];
    then
      printMsg "$cmdout" "cmd"
      printMsg "Stopping daemon failed" "cmd"
    else
      printMsg "Result: OK" "cmd"
    fi

    printMsg "Cleaning USB module" "cmd"

    clean_usb_module

    if [ "$ret_clean_usb_module" != 0 ];
    then
      printMsg "$cmdout" "cmd"
      printMsg "Cleaning module failed" "cmd"
    fi

    printMsg "Compiling usb module" "cmd"

    compile_usb_module

    create_usb_dir_tree
  fi
}

error_unknow_usb_module ()
{
  printMsgNoDot "Error:" "cmd"
  printMsgNoDot "$(${SEDCOMMAND} -i /make/d ${USBERRORFILE})"  "cmd"

}

error_kernel_usb_module ()
{
  printMsgNoDot "Support for USB forwarding over the network will not"    "cmd" 
  printMsg      "be available"                                            "cmd"
  printMsgNoDot "To compile USB module be sure that Linux kernel headers" "cmd"
  printMsg      "are available. Then update this installation"            "cmd"
}

check_error_kernel_usb_module ()
{
  ret_check_error_kernel_usb_module=0

  RETURN=$(${SEDCOMMAND} /make/d $USBERRORFILE);

  if [ -n "$RETURN" ];
  then
    return 0
  fi

  ret_check_error_kernel_usb_module=1

  return 0
}

stop_usb_daemon ()
{
  ret_stop_usb_daemon=0

  if [ ! -x "${NXUSBSCRIPT}" ] && [ -e "${NXUSBSCRIPT}" ];
  then
    return 0
  fi

  output=`$NXUSBSCRIPT "" "" --stop`;
  ret=$?

  if [ "$output" != "The daemon is not launched." ];
  then
    if [ $ret != 0 ]
    then
      ret_stop_usb_daemon=$ret
    fi
  fi

  output=`$NXUSBSCRIPT "" "" --unload`;
  ret=$?

  if [ "$output" != "The module is not loaded." ];
  then
    if [ $ret != 0 ]
    then
      ret_stop_usb_daemon=$ret
    fi
  fi

  $NXUSBSCRIPT "" "" --cleanup

  return 0
}

make_command_usb_module ()
{
  COMMAND=$1
  ret_make_command_usb_module=0

  USBISSUEFILE="none"
  USBCOMPILE="yes"

  if [ "x$system" = "xredhat" ];
  then
    if [ -e "/etc/issue" ];
    then
      USBISSUEFILE="/etc/issue"
    elif [ -e "/etc/redhat-release" ];
    then
      USBISSUEFILE="/etc/redhat-release"
    fi
  fi

  if [ "x$USBISSUEFILE" != "xnone" ];
  then
    USBVERS=`$CATCOMMAND $USBISSUEFILE | $GREPCOMMAND release | $SEDCOMMAND -e 's/.*release //' | $SEDCOMMAND -e 's/ .*//'`

    if [ "x$USBVERS" = "x6.0" ];
    then
      USBCOMPILE="no"
    fi
  fi

  if [ "x$USBCOMPILE" = "xyes" ];
  then
    cur_dir=`${PWDCOMMAND}`

    cd $USBKERNELDIR/

    ${MAKECOMMAND} $COMMAND 1> /dev/null 2> $USBERRORFILE 
    ret=$?

    if [ $ret != 0 ];
    then
      ret_make_command_usb_module=$ret

      cd "${cur_dir}"

      return 0
    fi

    if [ "x$COMMAND" != "xclean" ];
    then
      if [ ! -d "${NX_ROOT}/bin/drivers" ];
      then
        commandMkDir "${NX_ROOT}/bin/drivers" "warn"
      fi

      commandCp "./nxusb.ko" "${NX_ROOT}/bin/drivers/"
    fi

    cd "${cur_dir}"
  fi

  return 0
}

clean_usb_module ()
{
  #
  # Cleaning usb module.
  #

  make_command_usb_module clean
  ret_clean_usb_module=$?
  commandRm "${NX_ROOT}/bin/drivers/nxusb.ko"

  return 0
}

compile_usb_module ()
{
  #
  # Compiling usb module.
  #

  ret_compile_usb_module=0

  make_command_usb_module

  if [ $ret_make_command_usb_module != 0 ];
  then
    check_error_kernel_usb_module

    if [ $ret_check_error_kernel_usb_module = 1 ];
    then
      printMsg "Cannot compile USB module" "cmd"
      error_kernel_usb_module
      ret_compile_usb_module=1
      make_command_usb_module clean

      return 0
    fi

    printMsg "Cannot compile USB module" "cmd"
    error_unknow_usb_module
    ret_compile_usb_module=1
    make_command_usb_module clean

    return 0
  fi

  printMsg "Module compilation completed successfully" "cmd"

  if [ -f  "${NX_ROOT}/bin/drivers/nxusb.ko" ];
  then
    runCommand "${STRIPCOMMAND} --strip-debug ${NX_ROOT}/bin/drivers/nxusb.ko" "Cannot strip file: ${NX_ROOT}/bin/drivers/nxusb.ko" "warn"
  fi

  make_command_usb_module clean

  return 0
}

create_usb_dir_tree ()
{
  if [ ! -d "${NX_VAR_DIR}/run" ];
  then
    commandMkDir "${NX_VAR_DIR}/run" "warn"
    commandChmod "1777" "${NX_VAR_DIR}/run" "warn"
  fi
}

enablePrintConverters ()
{
  file=${NX_ROOT}/share/mimetypes
  tmpfile=${NX_ROOT}/share/mimetypes-tmp

  commandCp ${file}.sample $file

  command=`${GREPCOMMAND} "[a-zA-Z0-9]\{1,\}\/[a-zA-Z0-9\.\-]\{1,\}[	 ]\{1,\}\.[a-zA-Z0-9]\{1,\}" "$file"`

  ${ECHOCOMMAND} "$command" |

  while read line; do
    isSecond=0

    program=`${ECHOCOMMAND} $line | ${AWKCOMMAND} '{print $3}'`

    for x in $line; do
      if [ "$isSecond" = 1 ]; then
        secondProgram=$x

        break
      fi

      if [ "$x" = "|" ]; then
        isSecond=1
      fi
    done

    comment=`${ECHOCOMMAND} ${line:0:1}`

    path=`${ECHOCOMMAND} ${program:0:1}`

    if [ "$path" = "/" ]; then
      if [ -x "$program" ]; then
        exists=1
      else
        exists=0
      fi
    else
      if [ -x "/sbin/$program" ]; then
        exists=1
      elif [ -x "/usr/sbin/$program" ]; then
        exists=1
      elif [ -x "/usr/bin/$program" ]; then
        exists=1
      elif [ -x "/usr/local/bin/$program" ]; then
        exists=1
      elif [ -x "/usr/local/sbin/$program" ]; then
        exists=1
      else
        exists=0
      fi
    fi

    if [ "$exists" -eq 1 ]; then
      if [ "$isSecond" -eq 1 ]; then
        path=`${ECHOCOMMAND} ${secondProgram:0:1}`

        if [ "$path" = "/" ]; then
          if [ -x "$secondProgram" ]; then
            exists=2
          else
            exists=0
          fi
        else  
          if [ -x "/sbin/$secondProgram" ]; then
            exists=2
          elif [ -x "/usr/sbin/$secondProgram" ]; then
            exists=2
          elif [ -x "/usr/bin/$secondProgram" ]; then
            exists=2
          elif [ -x "/usr/local/bin/$secondProgram" ]; then
            exists=2
          elif [ -x "/usr/local/sbin/$secondProgram" ]; then
            exists=2
          else
            exists=0
          fi
        fi
      fi
    fi

    if [ "$exists" -eq  0 ]; then
      if [ "$comment" != "#" ]; then
        command=`${SEDCOMMAND} "s@^$line@#$line@" "$file" > "$tmpfile"`

        if [ "x${system}" = "xmacosx" ] && [ "x${system}" = "xsolaris" ]; then
          "$command"
        else
           $command
        fi

        ${MVCOMMAND} "$tmpfile" "$file"
      fi
    fi

    if [ "$exists" -gt 0 ]; then
      if [ "$comment" = "#" ]; then
        temp=`${ECHOCOMMAND} ${line:1}`

        command=`${SEDCOMMAND} "s@$line@$temp@" "$file" > "$tmpfile"`

        if [ "x${system}" = "xmacosx" ] && [ "x${system}" = "xsolaris" ]; then
          "$command"
        else
           $command
        fi

        ${MVCOMMAND} "$tmpfile" "$file"
      fi
    fi
done
}

setUpdateCfg ()
{
  commandChownChmod "root:${ROOTGNAME}" "644" "${NX_ROOT}/etc/update.cfg" "warn"
}

setAnywhereCfg ()
{
  if [ -f "${NX_ROOT}/etc/anywhere.cfg" ] && [ "x$system" != "xmacosx" ]; then
    commandChownChmod "root:${ROOTGNAME}" "644" "${NX_ROOT}/etc/anywhere.cfg" "warn"
  fi
  if [ -f "${NX_ROOT}/etc/network.cfg" ] && [ "x$system" != "xmacosx" ]; then
    commandChownChmod "root:${ROOTGNAME}" "644" "${NX_ROOT}/etc/network.cfg" "warn"
  fi
}

setFilePermissions ()
{
  commandChownChmod "root:${ROOTGNAME}" "444" "${NX_ROOT}/etc/version" "warn"

  if [ "x$system" = "xmacosx" ];
  then
    commandChmod "755" "${NX_ROOT}/share/X11/xkb" "warn"
    commandChownR "root:${ROOTGNAME}" "${NX_ROOT}/share/X11/xkb" "warn"
    commandChownR "root:${ROOTGNAME}" "${NX_ROOT}/share/images" "warn"
    commandChownR "root:${ROOTGNAME}" "${NX_ROOT}/share/documents" "warn"
  fi
}


createUUID ()
{
  if [ ! -f "${NX_ROOT}/etc/uuid" ] && [ -x "${NX_ROOT}/bin/nxkeygen" ];
  then
    runShCommand "NX_SYSTEM="${NX_ROOT}" LD_LIBRARY_PATH='${NX_ROOT}/lib:${NX_ROOT}/lib:$LD_LIBRARY_PATH' '${NX_ROOT}/bin/nxkeygen' -u > '${NX_ROOT}/etc/uuid'" "Cannot create ${NX_ROOT}/etc/uuid file" "cmd"

    if [ "x$LastCommand" != "x" ];
    then
      return 0
    fi
  fi
}

package_files=(
/bin/nxclient
/bin/nxclient.bin
/bin/nxauth
/bin/nxusbd
/bin/nxsh
/bin/nxexec
/bin/nxfsm
/bin/nxkb
/bin/nxexec.backup
/bin/nxmpeg
/bin/nxtunctl
/bin/nxprint
/bin/nxlpd
/bin/nxfs
/bin/nxfsserver
/bin/nxpost
/bin/nxc
/bin/nxssh
/bin/nxssh-add
/bin/nxssh-agent
/bin/nxkeygen
/scripts/restricted/nxfunct.sh
/scripts/restricted/nxusb.sh
/scripts/restricted/nxtun.sh
/scripts/nxtunfind.sh
/scripts/selinux/nx-unconfined.pp
/scripts/selinux/nx-system.pp
/etc/update.cfg
"/etc/keys/host/*"
/etc/version
"/lib/libqt.so*"
"/lib/libasound.so*"
#"/lib/libav.so*"
"/lib/libcrypto.so*"
"/lib/libssh.so*"
"/lib/libssl.so*"
"/lib/libexpat.so*"
"/lib/libfontconfig.so*"
"/lib/libfontenc.so*"
"/lib/libfreetype.so*"
"/lib/libmdnsd.so*"
"/lib/libnx.so*"
"/lib/libnxd.so*"
"/lib/libnxc.so*"
"/lib/libnxcau.so*"
"/lib/libnxcde.so*"
"/lib/libnxcim.so*"
"/lib/libnxcsl.so*"
"/lib/libnxslav.so*"
"/lib/libnxdiex.so*"
"/lib/libnxdift.so*"
"/lib/libnxdifb.so*"
#"/lib/libnxdb.so*"
"/lib/libnxesc.so*"
"/lib/libnxlo.so*"
"/lib/libnxup.so*"
"/lib/libnxn.so*"
"/lib/libnxne.so*"
"/lib/libnxs.so*"
"/lib/libnxcl.so*"
"/lib/libnxusb.so*"
"/lib/libnxfs.so*"
"/lib/libnxdixl.so*"
"/lib/libogg.so*"
"/lib/libopus.so*"
"/lib/libjpeg.so*"
"/lib/libjingle.so*"
"/lib/libpng.so*"
"/lib/libgif.so*"
"/lib/libpixman.so*"
"/lib/libspeex.so*"
"/lib/libspeexdsp.so*"
"/lib/libyuv.so*"
"/lib/libtheora.so*"
"/lib/libvp8.so*"
"/lib/libvmiso.so*"
"/lib/libvorbisenc.so*"
"/lib/libvorbisfile.so*"
"/lib/libvorbis.so*"
"/lib/libwebm.so*"
"/lib/libwebrtc.so*"
"/lib/libz.so*"
"/lib/libstdc++.so*"
"/lib/libpkcs11.so*"
/scripts/etc/localhost/client.cfg
/scripts/etc/localhost/client.cfg.sample
/scripts/setup/nxclient
/scripts/setup/install
"/share/cups/*"
"/share/documents/client/*"
/share/documents/client
"/share/images/dark/*"
"/share/images/player/win/*"
"/share/images/player/linux/*"
"/share/images/player/dark/*"
"/share/images/player/mac/*"
"/share/images/player/*"
"/share/images/linux/*"
"/share/images/mac/*"
"/share/images/win/*"
"/share/images/*"
"/share/keys/*"
/share/keyboards
/share/rgb
/share/X11/XErrorDB
/share/X11/XKeysymDB
/share/mimetypes
/share/mimetypes.sample
/share/icons/16x16/NoMachine-desktop.png
/share/icons/16x16/NoMachine-icon.png
/share/icons/16x16/NoMachine-recording.png
/share/icons/16x16/NoMachine-service.png
/share/icons/22x22/NoMachine-desktop.png
/share/icons/22x22/NoMachine-icon.png
/share/icons/22x22/NoMachine-recording.png
/share/icons/22x22/NoMachine-service.png
/share/icons/32x32/NoMachine-desktop.png
/share/icons/32x32/NoMachine-icon.png
/share/icons/32x32/NoMachine-recording.png
/share/icons/32x32/NoMachine-service.png
/share/icons/48x48/NoMachine-desktop.png
/share/icons/48x48/NoMachine-icon.png
/share/icons/48x48/NoMachine-recording.png
/share/icons/48x48/NoMachine-service.png
)

#"/lib/libusbsrvapitest.so*"

package_directories_recursive_before=(
/share/X11/xkb
/share/applnk/client
/share/applnk
/share/documents
/share/src/nxusb
/share/src
/bin/drivers
/scripts/init/nxtun
/scripts/init/nxusb
/scripts/init/nxfs
)

package_directories_empty=(
/scripts/etc/localhost
/scripts/etc
/scripts/setup
/scripts/selinux
/scripts/restricted
/scripts/init
/scripts
/share/cups
/share/documents/client
/share/documents
/share/images/dark
/share/images/player/win
/share/images/player/linux
/share/images/player/dark
/share/images/player/mac
/share/images/player
/share/images/linux
/share/images/mac
/share/images/win
/share/images
/share/kernel
/share/keys
/share/X11
/share/icons/16x16
/share/icons/22x22
/share/icons/32x32
/share/icons/48x48
/share/icons
/share
/bin
/lib
/etc/keys/host
/etc/keys
/etc
)

tab_lib_ver=(
libnxcau.so
libnxcde.so
libnxcim.so
libnxc.so
libnxdiex.so
libnxdift.so
libnxdifb.so
libnxdixl.so
libnxslav.so
libnx.so
)

processes_to_kill=(
nxclient.bin
nxclient
nxauth
nxusbd
nxsh
nxexec
nxfsm
nxkb
nxmpeg
nxtunctl
nxprint
nxlpd
nxfs
nxfsserver
nxpost
nxc
)

setRestrictedPermissions()
{
  if [ -f "${NXFUNCTSH}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXFUNCTSH}"
  else
    printMsg "No such file: ${NXFUNCTSH}" "warn"
  fi

  if [ "x${system}" != "xsolaris" ];
  then
    if [ -f "${NXUSBSCRIPT}" ];
    then
      ${SEDCOMMAND} -e 's:NX_VAR_PATH="":NX_VAR_PATH="'"${NX_VAR_DIR}"'":g'  "${NXUSBSCRIPT}" > "${NXUSBSCRIPT}".tmp
      commandRestoreFile "${NXUSBSCRIPT}" "tmp"

      commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXUSBSCRIPT}"
    else
      printMsg "No such file: ${NXUSBSCRIPT}" "warn"
    fi

    if [ -f "${NXTUNSCRIPT}" ];
    then
      commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXTUNSCRIPT}"
    else
      printMsg "No such file: ${NXTUNSCRIPT}" "warn"
    fi
  fi

  if [ "x${system}" = "xmacosx" ];
  then
    if [ -f "${NXTUNFINDSCRIPT}" ];
    then
      commandChownChmod "root:${ROOTGNAME}" "755" "${NXTUNFINDSCRIPT}"
    else
      printMsg "No such file: ${NXTUNFINDSCRIPT}" "warn"
    fi
  fi
}

resetRestrictedPermissions()
{
  commandChownChmodIfExist "root:${ROOTGNAME}" "0644" "${NXUSBSCRIPT}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "0744" "${NXFUNCTSH}"
}

procedureFinalUninstall ()
{
  commandRmDirRecursively "/var/NX" "cmd"
  commandChownR "root:${ROOTGNAME}" "${NX_ROOT}" "cmd"
  commandRm "/etc/pam.d/nx" "cmd"

  if [ "x${system}" = "xmacosx" ];
  then
    commandRm "${NX_ROOT}/share/mac/launchd/com.nomachine.uninstall.plist" "cmd"
    commandRm "${NX_ROOT}/share/mac/launchd/nxuninstall.sh" "cmd"
    commandRmDirIfExistEmpty "${NX_ROOT}/share/mac/launchd" "cmd"
    commandRmDirIfExistEmpty "${NX_ROOT}/share/mac" "cmd"
    commandRmDirRecursively "/Applications/NoMachine Server Preferences.app" "cmd"
    commandRmDirRecursively "/Applications/NoMachine Server Status.app" "cmd"
  else
    commandRmDirRecursively "${NX_MEDIA}" "cmd"
  fi
}

createMediaDir ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    return 0
  fi

  if [ ! -d "${NX_MEDIA}" ];
  then
    commandMkDir "${NX_MEDIA}" "cmd"
  fi

  commandChmod "1777" "${NX_MEDIA}" "cmd" 
}

upgradeFiles ()
{

  commandRmIfExist "${NX_ROOT}/bin/nxesd" "warn"
  commandRmIfExist "${NX_ROOT}/bin/nxkill" "warn"
  commandRmIfExist "${NX_ROOT}/bin/nxservice" "warn"
  commandRmIfExist "${NX_ROOT}/bin/nxssh" "warn"

  commandRmFiles "${NX_ROOT}/lib/libXcomp.so" "warn"
  commandRmFiles "${NX_ROOT}/lib/libXcompsh.so" "warn"
  commandRmFiles "${NX_ROOT}/lib/libcrypto.so.0." "warn"
  commandRmFiles "${NX_ROOT}/lib/libpng12.so" "warn"

  #commandRm "${NX_ROOT}/share/keymaps-windows" "warn"
  commandRm "${NX_ROOT}/share/documents/client/cups-info" "warn"

  commandRmIfExist "/etc/xdg/menus/applications-merged/NoMachine-dir.menu" "warn"

  if [ "x${NX_MPKG_PACKAGE}" != "xplayer" ];
  then
    commandRmDirRecursively "${NX_ROOT}/share/applnk" "warn"
    commandRmDirRecursively "${NX_ROOT}/share/fonts" "warn"
    commandRmDirRecursively "${NX_ROOT}/share/icons" "warn"

    commandRmIfExist "${NX_ROOT}/share/images/about-down.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/about-up.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/connect-01.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/connect-02.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/connect-03.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/connect-04.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/connect-fail-01.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/folder-shared-disabled.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/folder-shared.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/kill-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/kill.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/logo-small.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/logo.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/monitor-arrow-over.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/monitor-arrow.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/monitor-icon.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/monitor-user-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/multimedia.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/new-session-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/new-session.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/printer-default-icon-disabled.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/printer-default-icon.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/printer-icon-disabled.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/printer-icon.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/printer-shared-disabled.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/printer-shared.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/pulldown-close.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/pulldown-suspend.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/pulldown-terminate.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/refresh-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/refresh.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/remove-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/remove.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/sharing.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/session-stats-01-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/session-stats-01.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/session-stats-02-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/session-stats-02.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/terminate-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/terminate.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/view-log-dsb.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/view-log.png" "warn"
    commandRmIfExist "${NX_ROOT}/share/images/wizard.png" "warn"
  fi
}

removeLeftovers ()
{

  commandRmIfExist "${NX_ROOT}/bin/nxupnp" "warn"
  commandRmIfExist "/etc/pam.d/nxsshd" "warn"

  commandRmIfExist "/usr/share/applications/NoMachine-help.desktop" "warn"
  commandRmIfExist "/usr/share/applications/NoMachine-help-unity.desktop" "warn"
  commandRmIfExist "/usr/share/applications/NoMachine-nxr.desktop" "warn"

  if [ -w "/etc/gnome/defaults.list" ];
  then
    $SEDCOMMAND 's|\(application/nx-recording.*\)NoMachine-nxr.desktop;|\1|' /etc/gnome/defaults.list > /etc/gnome/defaults.list.tmp
    commandRestoreFile "/etc/gnome/defaults.list" "tmp"
  fi

  if [ "x${system}" != "xmacoscx" ] && [ -d "/usr/share/gnome/applications/" ];
  then
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-base.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-base-unity.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-base-xfce.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-nxs.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-nxv.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-nxr.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-player-base.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-player-base-unity.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-player-base-xfce.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-status.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-status-unity.desktop" "warn"
    commandRmIfExist "/usr/share/gnome/applications/NoMachine-status-xfce.desktop" "warn"
  fi

  if [ "x${system}" = "xmacosx" ];
  then
    commandRmIfExist "/Library/LaunchDaemons/com.nomachine.nxusb.plist" "warn"

    if [ -d "/System/Extensions/nxusb.kext" ];
    then
      commandRmDirRecursively "/System/Extensions/nxusb.kext" "cmd"
    fi

    if [ -d "/Library/Extensions/nxusb.kext" ];
    then
      commandRmDirRecursively "/Library/Extensions/nxusb.kext" "cmd"
    fi

    runCommand "${RMCOMMAND} -fr '/Library/Extensions/nxusb'*" "Cannot remove leftovers '/Library/Extensions/nxusb'*" "warn"
    runCommand "${RMCOMMAND} -fr '/System/Extensions/nxusb'*" "Cannot remove leftovers '/System/Extensions/nxusb'*" "warn"
  fi

  removeOldLibraries

  if [ "x${upgrade}" = "x1" ];
  then
    upgradeFiles
  fi

}

##########################################################################
############################  XDG  #######################################
##########################################################################

removeXDGIcons()
{
  printMsg "Removing XDG Icons" "cmd"
  ret_removeXDGIcons=0

  for size in 16 22 32 48; do

    for icon_name in desktop icon recording service; do

      #runCommand "${XDGICONRESOURCECOMMAND} uninstall --context apps --mode system --size '$size' 'NoMachine-$icon_name'" "Cannot uninstall icon 'NoMachine-$icon_name'" "cmd"
      (${XDGICONRESOURCECOMMAND} uninstall --context apps --mode system --size "$size" "NoMachine-$icon_name" >> "${LOGFILE}" 2>&1 ) &


    done
  done
}

installXDGIcons ()
{
  printMsg "Installing XDG Icons" "cmd"

  ret_createXDGIcons=0

  for size in 16 22 32 48; do

    for icon_name in desktop icon recording service; do

      icon_file="$shareNXPath/icons/$size"x"$size/NoMachine-$icon_name.png"

      #runCommand "${XDGICONRESOURCECOMMAND} install --context apps --mode system --size '$size' '$icon_file' 'NoMachine-$icon_name'" "Cannot install icon 'NoMachine-$icon_name'" "cmd"
      (${XDGICONRESOURCECOMMAND} install --noupdate --context apps --mode system --size "$size" "$icon_file" "NoMachine-$icon_name" >> "${LOGFILE}" 2>&1 ) &

      #  if [ ${ret_runCommand} != 0 ];
      # then
      #   removeXDGIcons_player
      #   ret_createXDGIcons=1
      #   return 0
      # fi

    done
  done

  return 0
}

addIconAssocXDG ()
{
  if [ "${NX_ROOT}" != "/usr/NX" ]
  then
    if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine-nxs.desktop" > "${NX_XDG}/NoMachine-nxs.desktop.tmp"
    then
      commandRestoreFile "${NX_XDG}/NoMachine-nxs.desktop" "tmp" "warn"
    fi

    if ${SEDCOMMAND} -e 's:/usr/NX:'"$NX_ROOT"':' < "${NX_XDG}/NoMachine-nxv.desktop" > "${NX_XDG}/NoMachine-nxv.desktop.tmp"
    then
      commandRestoreFile "${NX_XDG}/NoMachine-nxv.desktop" "tmp" "warn"
    fi
  fi

  runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine-nxs.desktop' '${NX_XDG}/NoMachine-nxv.desktop'" "Cannot create icon associations for nxv and nxs files" "cmd"

}

removeIconAsocXDG ()
{
  runCommand "${XDGDESKTOPMENUCOMMAND} uninstall --mode system 'NoMachine-nxs.desktop' 'NoMachine-nxv.desktop'" "Cannot remove icon associations for nxv and nxs files" "cmd"

  # Those files are not removed on some OS
  commandRmIfExist "/usr/share/applications/NoMachine-nxs.desktop" "warn"
  commandRmIfExist "/usr/share/applications/NoMachine-nxv.desktop" "warn"

}
########################################################################################################
updateSystemResourcesDatabase ()
{
  command="${UPDATEMIMEDATABASECOMMAND} -v"
  outCommand=`${BASHSHELL} -c "$command" 2>&1`

  if [ $? = 0 ];
  then
    printMsgDebug "Updating MIME database"

    command="${UPDATEMIMEDATABASECOMMAND} '/usr/share/mime'"
    outCommand=`${BASHSHELL} -c "$command" 2>&1`
    if [ $? != 0 ];
    then
      printMsg "Error while updating MIME database" "warn"
    fi
  else
    printMsg "Cannot update MIME database" "warn"
  fi

  if [ "${system}" != "solaris" ];
  then
    outCommand=`${BASHSHELL} -c "${UPDATEDESKTOPDATABASECOMMAND}" 2>&1`

    if [ $? != 0 ];
    then
      printMsg "Error while updating desktop database" "warn"
    fi
  fi

  commandRmIfExist "/usr/share/icons/hicolor/icon-theme.cache"
  commandRmIfExist "/usr/share/icons/gnome/icon-theme.cache"
}

########################################################################################################

__installResources__ ()
{
  printMsgDebug "Installing client resources"

  setIconVariables

  installIcon "NoMachine-icon.png"
  installIcon "NoMachine-desktop.png"
  installIcon "NoMachine-recording.png"
  installIcon "NoMachine-service.png"

  if [ "x${GTKUPDATEICONCACHECOMMAND}" != "x" ];
  then
    runCommand "${GTKUPDATEICONCACHECOMMAND} --force '${THEME_DIR}'" "${RUNCOMMAND_NO_ERROR_MESSAGE}"
  fi

}

__installResourcesXDG__ ()
{
  printMsgDebug "Installing client resources XDG"

  ret_updateXDGIcons="0";

  installXDGIcon "NoMachine-icon.png" "NoMachine-icon"
  installXDGIcon "NoMachine-desktop.png" "NoMachine-desktop"
  installXDGIcon "NoMachine-recording.png" "NoMachine-recording"
  installXDGIcon "NoMachine-service.png" "NoMachine-service"

  if [ "x${ret_updateXDGIcons}" = "x1" ];
  then
    (${XDGICONRESOURCECOMMAND} forceupdate)
  fi

  createXDGMime "${XDG_MIME_FILE}"

  addIconAssocXDG
}

__uninstallResources__ ()
{
  printMsgDebug "Uninstalling client resources"

  setIconVariables

  removeIcon "NoMachine-icon.png"
  removeIcon "NoMachine-desktop.png"
  removeIcon "NoMachine-recording.png"
  removeIcon "NoMachine-service.png"

  if [ "x${GTKUPDATEICONCACHECOMMAND}" != "x" ];
  then
    runCommand "${GTKUPDATEICONCACHECOMMAND} --force '${THEME_DIR}'" "${RUNCOMMAND_NO_ERROR_MESSAGE}"
  fi
}

__uninstallResourcesXDG__ ()
{
  printMsgDebug "Uninstalling client resources XDG"

  removeIconAsocXDG
  removeXDGMime "${XDG_MIME_FILE}"

  removeXDGIcon "NoMachine-icon"
  removeXDGIcon "NoMachine-desktop"
  removeXDGIcon "NoMachine-recording"
  removeXDGIcon "NoMachine-service"
}

########################################################################################################
procedureInstall ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    PACKAGE_NAME="player"

    getPackagePath "${PACKAGE_NAME}"
    if [ ${ret_getPackagePath} = 0 ];
    then
      if [ "x${ret_packagePath}" = "x${NX_ROOT}" ];
      then
        restoreContextForInstalationDir

        if [ "x${system}" = "xmacosx" ] && [ -f "${NX_ROOT}/share/mimetypes" ];
        then
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxclient" --update ${SYSTEM}
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --update ${SYSTEM}
        else
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxclient" --install ${SYSTEM}
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --install ${SYSTEM}
        fi

        return 0
      else
        getProductName "${PACKAGE_NAME}"
        printMsg "${ret_getProductName} package is already installed in: ${ret_packagePath}"
        return 0
      fi
    else
      restoreContextForInstalationDir

      if [ "x${system}" = "xmacosx" ] && [ -f "${NX_ROOT}/share/mimetypes" ];
      then
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxclient" --update ${SYSTEM}
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --update ${SYSTEM}
      else
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxclient" --install ${SYSTEM}
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --install ${SYSTEM}
      fi

      return 0
    fi
  fi

  initializeOperation "install"
  printOperationInfo "install"

  removeLeftovers

  installSELinuxModule

  checkETCDirectory
  setRestrictedPermissions

  selinuxOperations
  setNxuexecPermisions
  setNxFsmPermisions

  if [ "${system}" = "solaris" ];
  then
    fixTempXDir__solaris
  fi

  if [ "x${NX_CHANGE_MODE}" != "x1" ];
  then
    installDevices
  fi

  installResources
  installUsb

  enablePrintConverters
  createMediaDir

  setFilePermissions
  createUUID

  getPAMPath

  if [ -d "${ret_getPAMPath}" ];
  then
      pamScriptName=`${BASENAMECOMMAND} "${NX_PAM_SCRIPT}" 2>&1`
      pamnxFile="${ret_getPAMPath}/${pamScriptName}"
  fi

  if [ ! -f "${pamnxFile}" ];
  then
    installnxPAMScript
  fi

  setUpdateCfg
  setAnywhereCfg

  isInstalledProduct node
  addUpdateDBFile "${ret_isInstalledProduct}"

  printSummaryInfo "install"

  exit 0
}


procedureUninstall ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    PACKAGE_NAME="player"

    getPackagePath "${PACKAGE_NAME}"

    if [ ${ret_getPackagePath} = 0 ];
    then
      if [ "x${ret_packagePath}" = "x${NX_ROOT}" ];
      then
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --uninstall
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxclient" --uninstall

        return 0
      else
        getProductName "${PACKAGE_NAME}"
        printMsg "Standalone ${ret_getProductName} package is installed in another directory"

        return 0
      fi
    else
      getProductName "${PACKAGE_NAME}"
      printMsg "Standalone ${ret_getProductName} package is not installed"

      return 0
    fi
  fi

  initializeOperation "uninstall"

  uninstallUsb

  resetRestrictedPermissions

  if [ "x${system}" = "xmacosx" ];
  then
    commandRm "${NX_ROOT}/../MacOS/nxclient" "warn"
    commandRmDirIfExistEmpty "${NX_ROOT}/../MacOS" "warn"
    commandRmDirRecursively "${NX_ROOT}/../Resources" "warn"
  fi

  removeETCDirectory
  uninstallResources

  if [ "x${system}" = "xmacosx" ];
  then
    isInstalledOtherMacPackage "${NX_MPKG_PACKAGE}"

    if [ ${ret_isInstalledOtherMacPackage} = 0 ];
    then
      uninstallDevices
    fi
  else
    uninstallDevices
  fi

  removeSELinuxModule

  procedureFinalUninstall

  printOperationInfo "uninstall"
  printSummaryInfo "uninstall"

  exit 0
}

procedureUpdate ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    getProductName "${PACKAGE_NAME}"
    printMsg "Standalone ${ret_getProductName} package is not installed"
    return 0
  fi

  initializeOperation "update"

  isInstalledClient3
  if [ "x${ret_isInstalledClient3}" = "x1" ];
  then
    upgrade=1
  fi

  printOperationInfo "update" "${upgrade}"

  if [ "x${UPDATETYPE}" = "xauto" ] &&
     [ -f "${NX_ROOT}/nomachine_automatic_update.deb" ] &&
     [ -f "${NX_ROOT}/nomachine_automatic_update.rpm" ];
  then
    installIncreaseVersionPackage
  fi

  installSELinuxModule

  checkETCDirectory

  setRestrictedPermissions

  removeLeftovers

  selinuxOperations
  setNxuexecPermisions
  setNxFsmPermisions

  installResources
  #updateResources
  updateUsb

  if [ "x${NX_CHANGE_MODE}" != "x1" ];
  then
    installDevices
  fi

  enablePrintConverters
  createMediaDir

  setFilePermissions
  createUUID

  setUpdateCfg
  setAnywhereCfg

  isInstalledProduct node
  addUpdateDBFile "${ret_isInstalledProduct}"

  printSummaryInfo "update" "${upgrade}"

  exit 0
}

installPersonal()
{
  initializeOperation "install"
  printOperationInfo "install"

  printSummaryInfo "install"
}

uninstallPersonal()
{
  NX_PERSONAL=1
  initializeOperation "uninstall"
  printOperationInfo  "uninstall"

  removeETCDirectoryPersonal
  cleanPackageFiles

  printSummaryInfo "uninstall"
  exit 0
}

updatePersonal()
{
  initializeOperation "update"
  printOperationInfo "update"
}

runActionInstallService ()
{
  LOGFILE=${INSTALLOG}
  initializeLogFile	

  installDevices
}

runActionPackage ()
{
  empty=""
}


runAction
