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


PACKAGE_NAME="node"
VERSION="9.2.18"
PRODUCT_NAME="NoMachine Node $VERSION"
CONFIG_VERSION="4.0"

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

CONFIG_FILE="$NX_ROOT/etc/node.cfg"
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/install.log"
UPDATELOG="$NX_VAR_DIR/log/update.log"
UNINSTALLOG="$NX_VAR_DIR/log/uninstall.log"

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

SETUP_SCRIPT=1



OLD_NX_LOCALIZATION="/usr/NX"
DEFAULT_SEPATH="$OLD_NX_LOCALIZATION"

if [ "x$TMPDIR" = "x" ];
then
  TMP_FOLDER="/tmp"
else
  TMP_FOLDER="$TMPDIR"
fi

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

if [ -x "/sbin/start" ]
then
  STARTCOMMAND="/sbin/start"
else
  STARTCOMMAND="start"
fi

if [ -x "/sbin/stop" ]
then
  STOPCOMMAND="/sbin/stop"
else
  STOPCOMMAND="stop"
fi

if [ -x "/sbin/status" ]
then
  STATUSCOMMAND="/sbin/status"
else
  STATUSCOMMAND="status"
fi

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

  lsbPath="/etc/lsb-release"
  os_out=""
  wantedOS="$1"
  searchedFile=""
  ret_getLinuxNameFromFiles="1"

  if [ -f "$lsbPath" ];
  then
    os_out=$(${GREPCOMMAND} '\(\(NAME\)\|\(DISTRIB_ID\)\)=.*'"${wantedOS}"'.*$' "$lsbPath" 2>/dev/null || test 1)
  fi

  if [ "x$os_out" = "x" ];
  then

    if [ -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)

  fi

  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
      system=ubuntu
    fi

    getLinuxNameFromFiles "LinuxMint"

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

    getLinuxNameFromFiles "elementary"

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

    return 0
  fi

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

    DISTRO_FILE="/etc/arch-release"

    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="semodule"
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="expr"
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"
elif [ -x "/usr/bin/systemctl" ];
then
  SYSTEMCTLCOMMAND="/usr/bin/systemctl"
else
  SYSTEMCTLCOMMAND="systemctl"
fi

if [ -x "/sbin/initctl" ];
then
  INITCTLCOMMAND="/sbin/initctl"
elif [ -x "/bin/initctl" ];
then
  INITCTLCOMMAND="/bin/initctl"
else
  INITCTLCOMMAND="initctl"
fi

if [ -x "/sbin/ldconfig" ];
then
  LDCONFIGCOMMAND="/sbin/ldconfig"
elif [ -x "/usr/sbin/ldconfig" ];
then
  LDCONFIGCOMMAND="/usr/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/X11/lxterminal" ];
then
  LXTERMINALCOMMAND="/usr/bin/X11/lxterminal"
elif [ -x "/usr/bin/lxterminal" ];
then
  LXTERMINALCOMMAND="/usr/bin/lxterminal"
elif [ -x "/bin/lxterminal" ];
then
  LXTERMINALCOMMAND="/bin/lxterminal"
else
  LXTERMINALCOMMAND="lxterminal"
fi

if [ -x "/usr/bin/X11/deepin-terminal" ];
then
  DEEPINTERMINALCOMMAND="/usr/bin/X11/deepin-terminal"
elif [ -x "/usr/bin/deepin-terminal" ];
then
  DEEPINTERMINALCOMMAND="/usr/bin/deepin-terminal"
elif [ -x "/bin/deepin-terminal" ]
then
  DEEPINTERMINALCOMMAND="/bin/deepin-terminal"
else
  DEEPINTERMINALCOMMAND="deepin-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

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

if [ -x "/usr/bin/fuser" ];
then
  FUSERCOMMAND="/usr/bin/fuser"
elif [ -x "/bin/fuser" ];
then
  FUSERCOMMAND="/bin/fuser"
else
  FUSERCOMMAND="fuser"
fi

if [ -x "/usr/bin/setsid" ];
then
  SETSIDCOMMAND="/usr/bin/setsid"
elif [ -x "/bin/setsid" ];
then
  SETSIDCOMMAND="/bin/setsid"
else
  SETSIDCOMMAND="setsid"
fi

if [ -x "/usr/bin/umask" ];
then
  UMASKCOMMAND="/usr/bin/umask"
elif [ -x "/bin/umask" ];
then
  UMASKCOMMAND="/bin/umask"
else
  UMASKCOMMAND="umask"
fi

if [ -x "/usr/bin/cd" ];
then
  CDCOMMAND="/usr/bin/cd"
elif [ -x "/bin/cd" ];
then
  CDCOMMAND="/bin/cd"
else
  CDCOMMAND="cd"
fi

if [ -x "/usr/bin/tccutil" ];
then
  TCCUTILCOMMAND="/usr/bin/tccutil"
else
  TCCUTILCOMMAND="tccutil"
fi

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

if [ -x "/usr/bin/pkcheck" ];
then
  PKCHECKCOMMAND="/usr/bin/pkcheck"
else
  PKCHECKCOMMAND="pkcheck"
fi

if [ -x "/usr/bin/pactl" ];
then
  PACTLCOMMAND="/usr/bin/pactl"
elif [ -x "/bin/pactl" ];
then
  PACTLCOMMAND="/bin/pactl"
else
  PACTLCOMMAND="pactl"
fi

if [ -x "/usr/bin/ldd" ];
then
  LDDCOMMAND="/usr/bin/ldd"
elif [ -x "/bin/ldd" ];
then
  LDDCOMMAND="/bin/ldd"
else
  LDDCOMMAND="ldd"
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"
HTD_USR_CONFIG_FILE="${NX_ROOT}/etc/web.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}"
}

renameLog ()
{
  logname="$1"

  logdir=""

  if [ "$system" = "macosx" ];
  then
    logdir="${NXUSERHOME}/log/"
  else
    logdir="${NX_ROOT}/var/log/"
  fi

  if [ -d "${NXUSERHOME}" ] || [ -d "${NX_ROOT}" ]
  then
    if [ -f "${logdir}/nx${logname}" ]
    then
      ${MVCOMMAND} "${logdir}/nx${logname}" "${logdir}/${logname}"
    fi

    if [ "${logname}x" = "daemon.logx" ]
    then
      if [ -f "${logdir}/nxd.log" ]
      then
        ${MVCOMMAND} "${logdir}/nxd.log" "${logdir}/${logname}"
      fi
    fi
  fi
}

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_RUNNER_ROOT="RunnerRoot"
CFG_PLAYER_ROOT="PlayerRoot"
CFG_NODE_ROOT="NodeRoot"
CFG_SERVER_ROOT="ServerRoot"
CFG_NXUSER_HOME="NXUserHome"
CFG_CONNECT_ROOT="ConnectRoot"
CFG_WEBPLAYER_ROOT="WebPlayerRoot"
CFG_USBREDIRECTOR_ROOT="UsbRedirectorRoot"

CFG_NETWORK_DATABASE_ROOT="NetworkDatabaseRoot"
CFG_NETWORK_GATEWAY_ROOT="NetworkGatewayRoot"
CFG_NETWORK_MESSAGING_ROOT="NetworkMessagingRoot"
CFG_NETWORK_RELAY_ROOT="NetworkRelayRoot"
CFG_NETWORK_WEB_ROOT="NetworkWebRoot"

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}" = "xrunner" ];
  then
    ret_CFGRootName=$CFG_RUNNER_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
  elif [ "x${package}" = "xnetwork-database" ];
  then
    ret_CFGRootName=$CFG_NETWORK_DATABASE_ROOT
  elif [ "x${package}" = "xnetwork-gateway" ];
  then
    ret_CFGRootName=$CFG_NETWORK_GATEWAY_ROOT
  elif [ "x${package}" = "xnetwork-messaging" ];
  then
    ret_CFGRootName=$CFG_NETWORK_MESSAGING_ROOT
  elif [ "x${package}" = "xnetwork-relay" ];
  then
    ret_CFGRootName=$CFG_NETWORK_RELAY_ROOT
  elif [ "x${package}" = "xnetwork-web" ];
  then
    ret_CFGRootName=$CFG_NETWORK_WEB_ROOT
  else
    ${ECHOCOMMAND} "ERROR: Unknown package -- ${package}"
    ret_getRootCfgName=1
  fi
}

getConfigFileName ()
{
  #
  # Par1 - package name, i.e. runner, 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" = "xwebrunner" ];
  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 | "$TAILCOMMAND" -n1)

  if [ "x${grep_out}" = "x" ];
  then
    grep_out=$(${GREPCOMMAND} -E "^([[:space:]]){0,}[#]{0,1}([[:space:]]){0,}${variable}([[:space:]]){1,}" "${file_name}" 2>/dev/null | "$TAILCOMMAND" -n1)
  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 [ "x${grep_commented}" = "x0" ];
    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:]][[:space:]]*.*|'"${variable}"' '"${new_value}"'|' "${file_name}" > "${file_name}.tmp"
    else
      ${SEDCOMMAND} -e 's|^[[:space:]]*'"${variable}"'[[:space:]][[: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:]][[:space:]]*.*|'"${variable}"' '"${new_value}"'|' "${file_name}" > "${file_name}.tmp"
    else
      ${SEDCOMMAND} -e 's|^[[:space:]]*[#]*[[:space:]]*'"${variable}"'[[:space:]][[: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. runner, 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 [ "x${package_name}" = "xwebplayer" ]
  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
    runner)
      ret_getProductName="NoMachine Runner"
      ;;
    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"
      ;;
    network-database)
      ret_getProductName="NoMachine Network Database"
      ;;
    network-gateway)
      ret_getProductName="NoMachine Network Gateway"
      ;;
    network-messaging)
      ret_getProductName="NoMachine Network Messaging"
      ;;
    network-relay)
      ret_getProductName="NoMachine Network Relay"
      ;;
    network-web)
      ret_getProductName="NoMachine Network Web"
      ;;
  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

  if [ "${package_name}x" = serverx ]
  then
    command_out=$("${installation_path}/bin/nx${package_name}" --version --simple 2>/dev/null | ${HEADCOMMAND} -n 1 2>/dev/null)
  else
    command_out=$("${installation_path}/bin/nx${package_name}" --version 2>/dev/null | ${HEADCOMMAND} -n 1 2>/dev/null)
  fi

  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

    if [[ ${command_out} == *ERROR* ]];
    then
      version=""

      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. runner, 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
    if [[ "${NXSHELL}" = *"server" ]]
    then
      outCheckServerInstallation=$("${NXSHELL}" --version --simple  2>&1 | ${HEADCOMMAND} -n 1 2>/dev/null)
    else
      outCheckServerInstallation=$("${NXSHELL}" --version  2>&1 | ${HEADCOMMAND} -n 1 2>/dev/null)
    fi

    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

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

  if [ ! -f "${var_run}/server.shutdown" ];
  then
    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
  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: ${fileSrc} 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
}

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

  if [ -f "${fileSrc}" ];
  then
    runCommand "${MVCOMMAND} '${fileSrc}' '${fileDst}'" "Cannot move file: ${fileSrc} to: ${fileDst}" "${msgType}"
    ret_commandMv="${ret_runCommand}"
  fi
}

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

  ret_commandChcon=0

  if [ "x$SELINUX_ENABLED" = "x1" ];
  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 [ "x$SELINUX_ENABLED" = "x1" ];
  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 [ "x$SELINUX_ENABLED" = "x1" ];
  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 [ "x$SELINUX_ENABLED" = "x1" ];
  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}$\|${app} \|${app}$" | ${GREPCOMMAND} -v grep 2>/dev/null)

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

    ret_commandKillAllIfExist=${ret_commandKillAll}
  fi
}

commandTccutilReset()
{
  service="$1"
  bundleId="$2"
  msgType="$3"

  runCommand "$TCCUTILCOMMAND reset $service $bundleId" "Cannot reset service: $service for bundle: $bundleId" "$msgType"
  ret_commandTccutilReset="$ret_runCommand"
}

whichPath ()
{
  which_out=""
  if [ "x$1" != "x" ];
  then
    which_out=$(${WHICHCOMMAND} $1 2>/dev/null | ${HEADCOMMAND} -1 | ${GREPCOMMAND} -v "no $1 in" 2>/dev/null | $CATCOMMAND)
  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
}

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_ENV}" != "x" ];
  then
    INSTALL_PATH="${NX_PATH_ENV}"
    return 0
  fi

  getPackagePath "$PACKAGE_NAME"

  if [ "x$ret_packagePath" != "x" ];
  then
    INSTALL_PATH="$($DIRNAMECOMMAND "$ret_packagePath")"
    return 0
  fi
  
  if [ "x${NX_PATH_RELOCATE}" != "x" ];
  then
    INSTALL_PATH="${NX_PATH_RELOCATE}"
    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 and later."
  ${ECHOCOMMAND} "       suse         SLED 10 and later, SLES 10 and later, Open SUSE 10 and later."
  ${ECHOCOMMAND} "       slackware"
  ${ECHOCOMMAND} "       mandriva     Mandriva 2009 and later."
  ${ECHOCOMMAND} "       debian       Debian 4.0 and later."
  ${ECHOCOMMAND} "                    Ubuntu 8.04 and later."
  ${ECHOCOMMAND} "       fedora       Fedora 10 and later."
}

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
      if [ -d /run/systemd ];
      then
        runCommand "${SYSTEMCTLCOMMAND} restart nxserver.service" "Cannot enable systemd service: $1" "error"
      else
        printMsg "Dir /run/systemd doesn't exist" "warn"
      fi
    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_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 [ "x${ret_canUninstall3}" = "x0" ];
  then
    return 0
  fi

  isInstalled_3 "1"
  if [ "x${ret_isInstalled_3}" != "x0" ] || [ ! -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 nxrunner 3.X.
    #

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

canUninstall3 ()
{
  #
  # This function is executed only on update from NX 3.X
  #

  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
        if [ -f "${NX_ROOT}/etc/node.lic" ];
        then
          license_file="${NX_ROOT}/etc/node.lic"
        else
          license_file="${NX_ROOT}/etc/server.lic"
        fi
      else
        license_file="${LICENSE_FILE}"
      fi

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

    fi
  fi

  file_lic=""

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

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


  if [ "x$file_lic" != "x" ];
  then
    ret_getLicenseAcronym=$(${AWKCOMMAND} '/^Product Id/ {print $3}' \
                                          "${file_lic}")
  elif [ -n "$NEW_LICENSE_ACRONYM" ];
  then
    ret_getLicenseAcronym="$NEW_LICENSE_ACRONYM"
  else
    printMsg "Cannot find license file or variable to read an acronym" "warn"
    return 0
  fi
 
  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
}

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}" = SEx ]; then
    NOMACHINE_LICENSE_POSTFIX=" Evaluation"
  elif [ "${1}" = SSx ]; 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" "SSx" "SEx")
  NOMACHINE_LICENSE_POSTFIX=""

  acronym_first_letter=""

  #
  # Checking license for linux ARM packages.
  #   First letter of license for linux ARM
  #   packages changed from "L" to "R". 
  #

  acronym_first_letter="${ACTUAL_LICENSE_ACRONYM:0:1}"

  if [ "${acronym_first_letter}x" = "Rx" ]
  then
    ACTUAL_LICENSE_ACRONYM=$("${ECHOCOMMAND}" "${ACTUAL_LICENSE_ACRONYM}" | "${SEDCOMMAND}" 's/^R/L/g')
  fi

  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" = "LTSC{i}" ];
    then
      NOMACHINE_EXTENSION=" Terminal Server Cluster${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LETS${i}" ];
    then
      NOMACHINE_EXTENSION=" Enterprise 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" = "LSBCS${i}" ];
    then
      NOMACHINE_EXTENSION=" Small Business Cloud Server${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LWCS${i}" ];
    then
      NOMACHINE_EXTENSION=" Workgroup Cloud Server${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LSBTS{i}" ];
    then
      NOMACHINE_EXTENSION=" Small Business Terminal 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" = "LETSN${i}" ];
    then
      NOMACHINE_EXTENSION=" Enterprise 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
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LECSC${i}" ];
    then
      NOMACHINE_EXTENSION=" Enterprise Cloud Server Cluster${NOMACHINE_LICENSE_POSTFIX}"
      break
    elif [ "${ACTUAL_LICENSE_ACRONYM}x" = "LECS${i}" ];
    then
      NOMACHINE_EXTENSION=" Enterprise 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:6:1}") = "s" ]) || \
         [ $("${ECHOCOMMAND}" "${dirperms:7:1}") != "r" ] || \
       !([ $("${ECHOCOMMAND}" "${dirperms:9:1}") = "x" ] || \
         [ $("${ECHOCOMMAND}" "${dirperms:9:1}") = "s" ] || \
         [ $("${ECHOCOMMAND}" "${dirperms:9:1}") = "t" ]);
    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}"
}

compareLicDate ()
{
  local licFile="$1"

  compareLicDate_ret=0
  
  licDate="$("$CATCOMMAND" "$licFile" | "$GREPCOMMAND" "Expiry" 2>/dev/null | "$SEDCOMMAND" 's/Expiry: *//g')"
  licDateSince1970="$("$DATECOMMAND" -d "$licDate" +%s)"
  nowDateSince1970="$("$DATECOMMAND" +%s)"

  if [ "$licDateSince1970" -lt "$nowDateSince1970" ];
  then
    compareLicDate_ret=1
  fi
}

checkLicenseExpirationDate ()
{
  if [ -x "$NXSHELL" ]
  then
    checkStr="$("${NXSHELL}" --subscription | "${GREPCOMMAND}" "expired" || true)"

    if [ "x${checkStr}" != "x" ];
    then
      printMsgInstall " " 0
      printMsgInstall "Your NoMachine subscription is expired, updating the software is no longer permitted." 0
      printMsgInstall "Please contact your NoMachine provider or the Support Team for renewal options." 0
      printMsgInstall " " 0

      exit 1
    fi
  fi
}

compareLicenseAcronyms ()
{
  ret_compareLicenseAcronyms=1
  
  new_license_acronym="${1}"
  old_license_acronym="${2}"
  
  new_license_acronym_sed=""

  new_acronym_first_letter=""
  old_acronym_first_letter=""

  #
  # Checking license for linux ARM packages.
  #  First letter of license for linux ARM
  #  packages changed from "L" to "R". 
  #

  new_acronym_first_letter="${new_license_acronym:0:1}"
  old_acronym_first_letter="${old_license_acronym:0:1}"

  if [ "${new_acronym_first_letter}x" = "Rx" ] && [ "${old_acronym_first_letter}x" = "Lx" ]
  then
    old_license_acronym=$("${ECHOCOMMAND}" "${old_license_acronym}" | "${SEDCOMMAND}" 's/^L/R/g')
  fi

  if [ "${new_license_acronym}" = "${old_license_acronym}" ];
  then 
    ret_compareLicenseAcronyms=0
    
  elif [ "${new_license_acronym}" != "${old_license_acronym}" ];
  then
    new_license_acronym_sed=$(${ECHOCOMMAND} "${new_license_acronym}" | \
                            ${SEDCOMMAND} s'/.$//')
    
    if [ "x${new_license_acronym: -1}" = "xU" ] || \
       [ "x${new_license_acronym: -1}" = "xE" ];
    then 
      if [ "${new_license_acronym_sed}E"  = "${old_license_acronym}" ] || \
         [ "${new_license_acronym_sed}S"  = "${old_license_acronym}" ] || \
         [ "${new_license_acronym_sed}SE" = "${old_license_acronym}" ] || \
         [ "${new_license_acronym_sed}SS" = "${old_license_acronym}" ] || \
         [ "${new_license_acronym_sed}PS" = "${old_license_acronym}" ] || \
         [ "${new_license_acronym_sed}"   = "${old_license_acronym}" ];
      then 
        ret_compareLicenseAcronyms=0
      fi
    fi
  fi
}

checkCustomAcronym ()
{

  #
  # Checking custom acronym is used only for
  #   normal linux packages. It does not apply
  #   to the ARM packages so "L" can be hardcoded.
  #

  old_acronym="${1}"
  replacement_acronym="${2}"
  test_acronym="${3}"

  if [[ "${test_acronym}" != "" ]]
  then
    if [[ "${old_acronym}" = "L${test_acronym}E" ]];
    then
      old_acronym="L${replacement_acronym}E"
    elif [[ "${old_acronym}" = "L${test_acronym}S" ]];
    then
      old_acronym="L${replacement_acronym}S"
    elif [[ "${old_acronym}" = "L${test_acronym}SE" ]];
    then
      old_acronym="L${replacement_acronym}SE"
    elif [[ "${old_acronym}" = "L${test_acronym}SS" ]];
    then
      old_acronym="L${replacement_acronym}SS"
    elif [[ "${old_acronym}" = "L${test_acronym}PS" ]];
    then
      old_acronym="L${replacement_acronym}PS"
    fi
  fi

  #
  # Checking if new and old acronyms match
  #

  compareLicenseAcronyms "${NEW_LICENSE_ACRONYM}" "${old_acronym}"

  ret_checkCustomAcronym=${ret_compareLicenseAcronyms}
}

updateOnlyIfServerIsTheSame ()
{
  is_runner="${1}"

  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

  block_update=0

  if [ "${is_runner}x" = "runnerx" ]
  then
    serverVersionFromAcronym "${OLD_LICENSE_ACRONYM}"

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

    exit 1
  fi

  compareLicenseAcronyms "${NEW_LICENSE_ACRONYM}" "${OLD_LICENSE_ACRONYM}"

  licVerFile=""

  if [ -r "$NX_ROOT/etc/server.lic" ];
  then
    licVerFile="$NX_ROOT/etc/server.lic"
  elif [ -r "$NX_ROOT/etc/node.lic" ];
  then
    licVerFile="$NX_ROOT/etc/node.lic"
  fi

  licBelow6="0"

  if [ "x$licVerFile" != "x" ];
  then
    grep_out="$($GREPCOMMAND "Subscription Version:" $licVerFile \
              2>/dev/null | $CATCOMMAND)"

    if [ "x$grep_out" = "x" ];
    then
      licBelow6="1"
    fi
  fi

  installedMainVer="0"

  if [ -r "$NX_ROOT/etc/version" ];
  then
    installedMainVer="$($CATCOMMAND $NX_ROOT/etc/version | \
                        $CUTCOMMAND -d '.' -f1)"
  fi

  letCrossUpdate="0"

  if  [ "x$NEW_LICENSE_ACRONYM" = "xLETSE" ];
  then
    package_name="nomachine-enterprise-terminal-server"
  elif [ "x$NEW_LICENSE_ACRONYM" = "xLCSE" ];
  then
    package_name="nomachine-cloud-server"
  elif [ "x$NEW_LICENSE_ACRONYM" = "xLTSNE" ];
  then
    package_name="nomachine-terminal-server-node"
  elif [ "x$NEW_LICENSE_ACRONYM" = "xLWE" ];
  then
    package_name="nomachine-workstation"
  elif [ "x$NEW_LICENSE_ACRONYM" = "xLTSE" ];
  then
    package_name="nomachine-terminal-server"
  fi

  packageManagmentInstalled="0"
  samePackageType="0"
  pkgMgmOut=""

  if [ "x$licBelow6" = "x1" ] && [ "$installedMainVer" -ge 6 ] && [ "$installedMainVer" -le 8 ];
  then

    packageDatabaseOut=""
    
    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 2>/dev/null | '$CATCOMMAND'" "Cannot query deb packages" "cmd"

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

        checkRPM="0"

        packageManagmentInstalled="1"

	 runCommand "PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin '$DPKGCOMMAND' --get-selections | '$GREPCOMMAND' -v '$package_name' | '$GREPCOMMAND' nomachine 2>/dev/null | '$CATCOMMAND'" "Cannot query deb packages" "cmd"

        if [ "x$package_name" = "xnomachine-terminal-server" ];
	 then
          runCommand "PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin '$DPKGCOMMAND' --get-selections | '$GREPCOMMAND' nomachine-terminal-server-node 2>/dev/null | '$CATCOMMAND'" "Cannot query deb packages" "cmd"
	 fi

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

          samePackageType="1"

        else

          pkgMgmOut="$outCommand"

        fi
      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 2>/dev/null | '$CATCOMMAND'" "Cannot query rpm packages" "cmd"

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

          pkgMgmOut="$outCommand"

          packageManagmentInstalled="1"
	    
          runCommand "'${RPMCOMMAND}' -qa | '$GREPCOMMAND' -v '$package_name' | '${GREPCOMMAND}' nomachine 2>/dev/null | '$CATCOMMAND'" "Cannot query rpm packages" "cmd"

          if [ "x$package_name" = "xnomachine-terminal-server" ];
          then
            runCommand "'${RPMCOMMAND}' -qa | '$GREPCOMMAND' nomachine-terminal-server-node 2>/dev/null | '$CATCOMMAND'" "Cannot query deb packages" "cmd"
          fi

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

            samePackageType="1"

          else

            pkgMgmOut="$outCommand"

          fi
        fi
      fi
    fi
  fi

  mgmPkgName=""
  
  if [ ${ret_compareLicenseAcronyms} -eq 0 ] && ([ "x$NEW_LICENSE_ACRONYM" = "xLCSE" ] ||  [ "x$NEW_LICENSE_ACRONYM" = "xLTSE" ] || \
     [ "x$NEW_LICENSE_ACRONYM" = "xLWE" ] || [ "x$NEW_LICENSE_ACRONYM" = "xLESE" ]) && [ "x$packageManagmentInstalled" = "x1" ] && \
     [ "x$samePackageType" = "x0" ] && [ "x$licBelow6" = "x1" ] && \
     [ "$installedMainVer" -ge 6 ];
  then
    block_update=1

    if [[ "x$pkgMgmOut" = *"nomachine-enterprise-terminal-server"* ]];
    then
      mgmPkgName=" Enterprise Terminal Server"
    elif [[ "x$pkgMgmOut" = *"nomachine-cloud-server"* ]];
    then
      mgmPkgName=" Cloud Server"
    elif [[ "x$pkgMgmOut" = *"nomachine-terminal-server-node"* ]];
    then
      mgmPkgName=" Terminal Server Node"
    fi
  fi
  
  if [ "x$installedMainVer" = "x5" ] || \
       ([ "x$licBelow6" = "x1" ] && [ "$installedMainVer" -ge 6 ] && \
          [ "x$samePackageType" = "x1" ]);
  then
    letCrossUpdate="1"
  fi

  #
  # Check not-supported-anymore products or products that have 
  # multi-product update possibility.
  #

  if [ ${ret_compareLicenseAcronyms} -eq 1 ];
  then

    block_update=1

    #
    # Enable updating Portal Server by Cloud Server.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "PS"

    if [ ${ret_checkCustomAcronym} -eq 0 ]
    then
      block_update=0
    fi

    #
    # Enable updating Cloud Server by Enterprise Terminal Server.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "ETS" "CS"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "x$installedMainVer" = "x5" ];
    then
      block_update=0
    fi

    #
    # Enable updating Enterprise Server by Enterprise Terminal Server.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "ETS" "ES"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "x$letCrossUpdate" = "x1" ];
    then
      block_update=0
    fi

    #
    # Enable updating Enterprise Server by Cloud Server.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "CS" "ES"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "x$installedMainVer" = "x5" ];
    then
      block_update=0
    fi

    #
    # Enable updating Workstation by Terminal Server Node.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "TSN" "W"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "x$installedMainVer" = "x5" ];
    then
      block_update=0
    fi

    #
    # Enable updating Terminal Server by Terminal Server Node.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "TSN" "TS"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "x$installedMainVer" = "x5" ];
    then
      block_update=0
    fi

    #
    # Enable updating Small Business by Small Business Terminal Server.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "SBTS" "SB"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "$installedMainVer" -le 7 ];
    then
      block_update=0
    fi

    #
    # Enable updating Cloud Server by Enterprise Cloud Server.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "ECS" "CS"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "$installedMainVer" -le  8 ];
    then
      block_update=0
    fi

    #
    # Enable updating Cloud Server by Enterprise Cloud Server Cluster.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "ECSC" "CS"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "$installedMainVer" -le  8 ];
    then
      block_update=0
    fi


    #
    # Enable updating Terminal Server Node by Enterprise Terminal Server Node.
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "ETSN" "TSN"

    if [ ${ret_checkCustomAcronym} -eq 0 ] && [ "$installedMainVer" -le  7 ];
    then
      block_update=0
    fi

    if [[ "x$NEW_LICENSE_ACRONYM" = *"CS"* ]] && [[ "x$OLD_LICENSE_ACRONYM" = *"CS"* ]];
    then
      block_update=0
    fi

    #
    # Enable updating Workstation by Workstation with new acronym (WS: since 9.0.113).
    #

    checkCustomAcronym "${OLD_LICENSE_ACRONYM}" "WS" "W"

    if [ ${ret_checkCustomAcronym} -eq 0 ]
    then
      block_update=0
    fi
  fi

  if [ ${block_update} -eq 1 ]
  then

    if [ "x$mgmPkgName" = "x" ];
    then 
      serverVersionFromAcronym "${OLD_LICENSE_ACRONYM}"
      INSTALLED_NOMACHINE="${NOMACHINE_EXTENSION}"
    else
      INSTALLED_NOMACHINE="$mgmPkgName"
    fi
    
    serverVersionFromAcronym "${NEW_LICENSE_ACRONYM}"

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

    exit 1
  fi
}

clusterStatus()
{
  ret_clusterStatus="0"

  clusterlist_output="$(${NXSHELL} --clusterlist | ${GREPCOMMAND} -o "[[:alnum:]]\.[[:alnum:]]*\.[[:alnum:]]*\." || true)"

  if [ "x${clusterlist_output}" != "x" ]
  then
    ret_clusterStatus="1"
  fi
}

showClusterLicenseInformation()
{
  if [[ "x${OLD_LICENSE_ACRONYM}" = "xLCS"* ]] || [[ "x${OLD_LICENSE_ACRONYM}" = "xLETS"* ]]
  then
    LANG=$(locale | ${GREPCOMMAND} "LANG=" | ${CUTCOMMAND} -d "=" -f 2-)

    if [[ "x${LANG}" != "xes"* ]] && [[ "x${LANG}" != "xde"* ]] && [[ "x${LANG}" != "xfr"* ]] &&\
       [[ "x${LANG}" != "xit"* ]] && [[ "x${LANG}" != "xpl"* ]] && [[ "x${LANG}" != "xpt"* ]] &&\
       [[ "x${LANG}" != "xru"* ]] && [[ "x${LANG}" != "xen"* ]]
    then
      LANG="en"
    fi

    serverVersionFromAcronym "${NEW_LICENSE_ACRONYM}"

    message_en="Upgrading to NoMachine${NOMACHINE_EXTENSION} will preserve all failover and high-availability functionalities already configured in the previous version. However, a new product tailored specifically for cluster is available at a more convenient price. Please contact the Sales Team to find out how to switch to${NOMACHINE_EXTENSION} Cluster."
    message_es="La actualización a NoMachine${NOMACHINE_EXTENSION} conservará todas las funcionalidades de conmutación por error y de alta disponibilidad ya configuradas en la versión anterior. Sin embargo, existe un nuevo producto adaptado específicamente para clúster a un precio más conveniente. Póngase en contacto con el equipo de ventas para saber cómo cambiar a${NOMACHINE_EXTENSION} Cluster."
    message_de="Beim Upgrade auf NoMachine${NOMACHINE_EXTENSION} bleiben alle Ausfallsicherungs- und Hochverfügbarkeitsfunktionen erhalten, die bereits in der Vorgängerversion konfiguriert waren. Ein neues Produkt, das speziell auf Cluster zugeschnitten ist, ist jedoch auch zu einem günstigeren Preis erhältlich. Bitte wenden Sie sich an unser Vertriebsteam, um zu erfahren, wie Sie zu${NOMACHINE_EXTENSION} Cluster wechseln können."
    message_fr="Avec une mise à niveau vers NoMachine${NOMACHINE_EXTENSION}, toutes les capacités de protection contre les pannes et de grande disponibilité déjà configurées dans la version précédente sont conservées. Toutefois, un nouveau produit conçu spécialement pour le cluster est disponible à un prix plus avantageux. Veuillez contacter l’Équipe de Vente pour découvrir comment passer à${NOMACHINE_EXTENSION} Cluster."
    message_it="L'aggiornamento a NoMachine${NOMACHINE_EXTENSION} manterrà tutte le funzionalità di failover e alta disponibilità già configurate nella versione precedente. Tuttavia, un nuovo prodotto su misura per il cluster è disponibile a un prezzo più vantaggioso. Contatta il nostro Team di Vendita per sapere come passare a${NOMACHINE_EXTENSION} Cluster."
    message_pl="Aktualizacja do serwera NoMachine${NOMACHINE_EXTENSION} zachowuje wszystkie funkcje przełączania awaryjnego i wysokiej dostępności, które zostały już skonfigurowane w poprzedniej wersji. W korzystniejszej cenie dostępny jest także nowy produkt dostosowany specjalnie dla rozwiązań klastrowych. Prosimy o kontakt z zespołem sprzedaży, aby uzyskać informacje o przejściu na${NOMACHINE_EXTENSION} Cluster."
    message_pt="A atualização para o NoMachine${NOMACHINE_EXTENSION} preserva todas as funcionalidades de failover e de elevada disponibilidade já configuradas na versão anterior. Porém, está disponível um novo produto adaptado especificamente a clusters e por um preço mais acessível. Contacte a Equipa de Vendas para saber como pode mudar para o${NOMACHINE_EXTENSION} Cluster."
    message_ru="При переходе на NoMachine${NOMACHINE_EXTENSION} будут полностью сохранены параметры высокой доступности и автоматического переключения при отказе, уже настроенные в предыдущей версии. Однако новый продукт, разработанный специально для кластеров, доступен по более выгодной цене. Обратитесь в отдел продаж, чтобы узнать, как перейти на${NOMACHINE_EXTENSION} Cluster."

    MESSAGE=""

    if [[ "x${LANG}" = "xes"* ]]
    then
      MESSAGE="${message_es}"
    elif [[ "x${LANG}" = "xde"* ]]
    then
      MESSAGE="${message_de}"
    elif [[ "x${LANG}" = "xfr"* ]]
    then
      MESSAGE="${message_fr}"
    elif [[ "x${LANG}" = "xit"* ]]
    then
      MESSAGE="${message_it}"
    elif [[ "x${LANG}" = "xpl"* ]]
    then
      MESSAGE="${message_pl}"
    elif [[ "x${LANG}" = "xpt"* ]]
    then
      MESSAGE="${message_pt}"
    elif [[ "x${LANG}" = "xru"* ]]
    then
      MESSAGE="${message_ru}"
    else
      MESSAGE="${message_en}"
    fi

    clusterStatus

    if [ -f "${NX_ROOT}/etc/version" ]
    then
      version=$("${CATCOMMAND}" "${NX_ROOT}/etc/version")
    fi

    if [ "x${ret_clusterStatus}" = "x1" ] && ([[ "${version}" = "7."* ]] || [[ "${version}" = "6."* ]])
    then
      printMsgInstall " " 0
      printMsgInstall "${MESSAGE}" 0
      printMsgInstall " " 0
    fi
  fi
}

#######################
####### END OF LICENSES
#######################

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 ()
{
  local serverInstalled="$1"

  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

  if [ "x$serverInstalled" = "x1" ];
  then
    commandChownChmod "${USER_NX}:${USER_NX}" "0644" "${var_db}/update" "warn"
  else
    commandChownChmod "root:${ROOTGNAME}" "0644" "${var_db}/update" "warn"
  fi
}

logBasicSystemInfo ()
{
  #
  # Writing basic data about package file
  # and platform.
  #

  getSystemName

  if [ "${system}x" = "macosxx" ]
  then

    if [[ "${PACKAGE_FILE}x" != "#MACOS_PACKAGE_FILE_NAME#x" ]]
    then    
      printMsg "Installing NoMachine from: ${PACKAGE_FILE} package" "onlylog"
    else    
      printMsg "Data about package are not available" "warn"
    fi

    getMacOSXVersion

    uname_output=$(${UNAMECOMMAND} -a)

    if [ "${uname_output}x" != "x" ]
    then    
      printMsg "System information: ${system} ${mac_ver_full} ${uname_output}" "onlylog"
    else    
      printMsg "System information are not available" "error" 
    fi
  else
    if [ "${PACKAGE_FILE}x" != "x" ]
    then    
      printMsg "Installing NoMachine from: ${PACKAGE_FILE} package" "onlylog"
    else    
      printMsg "Data about package are not available" "warn"
    fi

    getLinuxName
    getDistroVersion

    uname_output=$(${UNAMECOMMAND} -a)

    if [ "${uname_output}x" != "x" ]
    then    
      printMsg "System information: ${system} ${ret_DistroVersion} ${uname_output}" "onlylog"
    else    
      printMsg "System information are not available" "error" 
    fi
  fi
}

compareMD5 ()
{
  file_1="${1}"
  file_2="${2}"

  file_md5_1="0"
  file_md5_2="0"

  ret_compareMD5=0

  if [ -f "${file_1}" ]
  then
    file_md5_1=($("${MD5SUMCOMMAND}" "${file_1}"))
  fi

  if [ -f "${file_2}" ]
  then
    file_md5_2=($("${MD5SUMCOMMAND}" "${file_2}"))
  fi

  if [ "${file_md5_1}" = "${file_md5_2}" ]
  then
    ret_compareMD5=1
  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
  
  if [ "${NX_ROOT: -1}" = "/" ]
  then
    getProcessPID "${NX_ROOT}bin/${nxapp}"
  else
    getProcessPID "${NX_ROOT}/bin/${nxapp}"
  fi

  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
}

#
# compareVersions version1 version2
#
# Function returns:
# 0 : versions are equal
# 1 : version1 is greater
# 2 : version2 is greater
#

compareVersions ()
{
  local i
  ret_compareVersions=0

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

  local IFS=.

  local ver1=($1)
  local ver2=($2)

  #
  # fill empty fields in ver1 with zeros.
  #

  for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
  do
    ver1[i]=0
  done

  for ((i=0; i<${#ver1[@]}; i++))
  do
    if [ -z ${ver2[i]} ]
    then
      # fill empty fields in ver2 with zeros
      ver2[i]=0
    fi
    if [ ${ver1[i]} -gt ${ver2[i]} ]
    then
      ret_compareVersions=1
      return 0
    fi
    if [ ${ver1[i]} -lt ${ver2[i]} ]
    then
      ret_compareVersions=2
      return 0
    fi
  done
  return 0
}


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"
NX_GROUP="nx"
LPADMIN="_lpadmin"

createLogdirectory ()
{
  msgType="${1}"

  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 "775" "${NX_VAR_DIR}/log" "warn"
    fi
  else
    if [ "${msgType}x" != "x" ]
    then
      commandChmod "775" "${NX_VAR_DIR}/log" "${msgType}"
    else
      commandChmod "775" "${NX_VAR_DIR}/log" "warn"
    fi
  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=""

  if [ "${package_name}x" = "serverx" ]
  then
    cmd_version_2_and_3="/usr/NX/bin/nx$package_name --version --simple"
    cmd_version_4="/etc/NX/nx$package_name --version --simple"
  else
    cmd_version_2_and_3="/usr/NX/bin/nx$package_name --version"
    cmd_version_4="/etc/NX/nx$package_name --version"
  fi

  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}/web.cfg";;
      "webplayer" ) ret_getUsrConfigFile="${path}/cloud.cfg";;
    esac
}


checkSELinuxModule ()
{
  ret_checkSELinuxModule=""

  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="nx"
    fi

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

    if [ "x${out}" != "x" ];
    then
      ret_checkSELinuxModule="nx-unconfined-fedora24"
    fi

  fi
}

removeSELinuxCustomPath()
{
  if [ "x$NX_ROOT" != "x$DEFAULT_SEPATH" ] && \
     [ "x$SEMANAGECOMMAND" != "x" ] && [ -x "$SEMANAGECOMMAND" ];
  then
    runCommand "'$SEMANAGECOMMAND' fcontext -d -e '$DEFAULT_SEPATH' '$NX_ROOT'" \
               "${RUNCOMMAND_NO_ERROR_MESSAGE}"
  fi
}

setSELinuxCustomPath()
{
  if [ "x$NX_ROOT" != "x$DEFAULT_SEPATH" ] && \
     [ "x$SEMANAGECOMMAND" != "x" ] && [ -x "$SEMANAGECOMMAND" ];
  then
    seFileRule="$($SEMANAGECOMMAND fcontext -l | \
                  $GREPCOMMAND "$NX_ROOT.*=.*$DEFAULT_SEPATH" 2>/dev/null)"

    if [ "x$seFileRule" = "x" ];
    then
      runCommand "'$SEMANAGECOMMAND' fcontext -a -e '$DEFAULT_SEPATH' '$NX_ROOT'\
                 " "${RUNCOMMAND_NO_ERROR_MESSAGE}"
    fi
  fi  
}

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

  if [ "x${SEMODULECOMMAND}" != "x" ] && [ -x "${SEMODULECOMMAND}" ];
  then

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

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

      if [ $majorFedoraVersion -eq 24 ];
      then
        NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/nx-unconfined-fedora24.pp"
      elif [ $majorFedoraVersion -ge 25 ];
      then
        NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/fedora25/nx.pp"
      else
        NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/nx-unconfined.pp"
      fi
    elif [ "x${system}" = "xredhat" ];
    then

      #
      # Removing obsolete nx-unconfined-fedora24.pp from redhat.
      #

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

      if [ "x${out}" = "xnx-unconfined-fedora24" ];
      then
        runCommand "${SEMODULECOMMAND} -v -r $out" \
                   "Cannot remove obsolete SELinux module" "warn"
      fi

      getDistroVersion

      majorDstrVer=$(echo "$ret_DistroVersion" | ${CUTCOMMAND} -d '.' -f 1)

      if [ $majorDstrVer -ge 7 ];
      then
        NX_SELINUX_MODULE="${NX_ROOT}/scripts/selinux/nx.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

    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
        
        setSELinuxCustomPath

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

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

          printMsg "Restoring SELinux 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}" != "x" ];
    then
      runCommand "${SEMODULECOMMAND} -v -r $ret_checkSELinuxModule" \
          "Cannot remove custom SELinux module" "warn"
    fi
  fi
}

removeSELinuxSettings ()
{
  removeSELinuxCustomPath
  removeSELinuxModule
}

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
      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=""

    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/startplasma-x11"
                              "/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/startplasma-x11"
                              "/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/xfreerdp"
                              "/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
      for ((i=0;i<${#alternative_paths[@]};i++)); do
        if [ -x "${alternative_paths[${i}]}" ];
        then
          commandOut="${alternative_paths[${i}]}"
          ret_checkAvailabilitySession=1
          return 0
        fi
      done

      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}"vpn"
}

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}"
}

addVPNSessionType ()
{
  vpn_session_list=",vpn"

  getAvailableSessionKey "${NODE_USR_CONFIG_FILE}"

  new_available_sessions_types="${available_sessions}${vpn_session_list}"

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

  getAvailableSessionKey "${SERVER_USR_CONFIG_FILE}"

  new_available_sessions_types="${available_sessions}${vpn_session_list}"

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

checkAvailableSessionTypes ()
{
  getListMissingSessionTypes

  getPreviousVersion

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

   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
   
   if [[ ("x${ret_getListMissingSessionTypes}" = "xvpn") &&\
         ("${major_version}" -le "8") ]];
   then
     addVPNSessionType

     ret_getListMissingSessionTypes=""
   fi

  fi
 
  if [ "x${ret_getListMissingSessionTypes}" != "x" ];
  then
    printMsgNoDot "Setup detected that these types of sessions are now available"
    printMsgNoDot "on the system: ${ret_getListMissingSessionTypes}"
    printMsgNoDot "but not in the NoMachine configuration. To enable them in the"
    printMsgNoDot "NoMachine configuration run:"
    printMsgNoDot "${NX_ROOT}/scripts/setup/nxnode --availablesessionsetup"
  else
    printMsgDebug "Cannot find new types of sessions."
  fi
}

untar_and_check ()
{
  wrapper_file="${1}"

  "${MVCOMMAND}" "${wrapper_file}" "${wrapper_file}.tar.gz"
  "${TARCOMMAND}" xzf "${wrapper_file}.tar.gz" -C "${NX_ROOT}/scripts/etc/"

  if [ -f "${wrapper_file}" ]
  then
    "${RMCOMMAND}" -rf "${wrapper_file}.tar.gz"
  else
    "${MVCOMMAND}" "${wrapper_file}.tar.gz" "${wrapper_file}"
  fi
}

unpackETCWrappers ()
{
  if [ "x${system}" = "xmacosx" ]
  then

    if [ -f ${NX_ROOT}/scripts/etc/nxnode ]
    then
      untar_and_check "${NX_ROOT}/scripts/etc/nxnode"
    fi

    if [ -f ${NX_ROOT}/scripts/etc/nxserver ]
    then
      untar_and_check "${NX_ROOT}/scripts/etc/nxserver"
    fi

    if [ -f ${NX_ROOT}/scripts/etc/nxwebplayer ]
    then
      untar_and_check "${NX_ROOT}/scripts/etc/nxwebplayer"
    fi
  fi
}

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

    if [ "x${PACKAGE_NAME}" = "xrunner" ] || [ "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

    if [ "x${PACKAGE_NAME}" = "xrunner" ] && [ "x${UPDATETYPE}" = "xauto" ]
    then
  
      if [ -f "${NX_ROOT}/scripts/etc/localhost/client.cfg" ] && [ ! -f "${NX_ROOT}/scripts/etc/localhost/runner.cfg" ]
      then
        $SEDCOMMAND 's|ClientRoot|RunnerRoot|' "${NX_ROOT}/scripts/etc/localhost/client.cfg" > "${NX_ROOT}/scripts/etc/localhost/client.cfg.backup"
        commandMv "${NX_ROOT}/scripts/etc/localhost/client.cfg.backup" "${NX_ROOT}/scripts/etc/localhost/runner.cfg"
      fi
    fi

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

    if [ "x${PACKAGE_NAME}" != "xrunner" ] && [ "x${PACKAGE_NAME}" != "xplayer" ] && [ "x$catalinaUpper" != "x1" ];
    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

    #
    # Removing obsolete client.cfg if exists.
    #

    commandRmIfExist "/etc/NX/${NX_MPKG_PACKAGE}/localhost/client.cfg"

    return
  fi

  if [ "x${PACKAGE_NAME}" = "xrunner" ] && [ $operation = "update" ];
  then
    commandInstall "root" "${ROOTGNAME}" "644" "${NX_ROOT}/scripts/etc/localhost/${PACKAGE_NAME}.cfg" "/etc/NX/${NX_MPKG_PACKAGE}/localhost/"
  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 "server" "${productNameToCheck}"
  servercfg=${ret_getConfigFileName}
  getConfigFileName "player" "${productNameToCheck}"
  playercfg=${ret_getConfigFileName}
  getConfigFileName "node" "${productNameToCheck}"
  nodecfg=${ret_getConfigFileName}

  if [ "x${packageName}" = "xrunner" ];
  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" ];
    then
      if [ -f "${playercfg}" ];
      then
        ret_checkSkippingUninstall=1
        return 0
      fi
    elif [ "x${productName}" = "xplayer" ];
    then
      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"
}

copyUninstallPlist ()
{
  if [ "$mac_ver_major" -ge "13" ];
  then
    commandCp "${NX_ROOT}/share/mac/launchd/$MAC_UNINSTALL_PLIST" "/Library/LaunchDaemons/$MAC_UNINSTALL_PLIST" "cmd"
  else
    commandCp "${NX_ROOT}/share/mac/launchd/com.nomachine.uninstall-legacy.plist" "/Library/LaunchDaemons/$MAC_UNINSTALL_PLIST" "cmd"
  fi
}

installMacUninstallAgent ()
{
  getMacOSXVersion
  
  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

  if [ "$mac_ver_major" -ge "12" ];
  then
    commandCpDir  "${NX_ROOT}/share/mac/launchd/NoMachine Uninstall.app" "/Library/Application Support/NoMachine/" "cmd"
    commandChownR "root:${ROOTGNAME}"  "/Library/Application Support/NoMachine/NoMachine Uninstall.app"
    commandChmod 0755 "/Library/Application Support/NoMachine/NoMachine Uninstall.app/Contents/MacOS/NoMachine Uninstall"

    if [ "$mac_ver_major" -ge "13" ];
    then
      commandCp "${NX_ROOT}/share/mac/launchd/com.nomachine.nomachineAgent.plist" "/Library/LaunchAgents/com.nomachine.uninstallAgent.plist" "cmd"
    else
      commandCp "${NX_ROOT}/share/mac/launchd/com.nomachine.nomachineAgent-legacy.plist" "/Library/LaunchAgents/com.nomachine.uninstallAgent.plist" "cmd"
    fi
  fi

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

  copyUninstallPlist

  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
      dialog_msg="${dialog_msg} <br> <br>Additional services were configured to run:"
    else 
      dialog_msg="${dialog_msg} <br> <br>An additional service was configured to run:"
    fi

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

printClusterInfo ()
{
  printMsgNoDot "Before being able to handle connections on this server"
  printMsgNoDot "you will have to configure the cluster, by telling it"
  printMsg      "who is the master and who is the slave"
  printMsgNoDot "To do that use the commands:"
  printMsgNoDot "nxserver --clusteradd --local <server> --master <IP>"
  printMsgNoDot "--slave <IP>"
  printMsgNoDot "nxserver --clusteradd <peer IP>"
}

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
}

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()
{
  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/nxrunner-${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 uninstalled 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"
                     auxOp4="Installation"
                     auxOp5="installation"
                     printSystemName=1
                     ;;
    "install-basic") auxOp1="Installing"
                     auxOp2="Install"
                     auxOp3="install"
                     auxOp4="Installation"
                     auxOp5="installation"
                     printSystemName=1
                     ;;
    "uninstall")     auxOp1="Uninstalling"
                     auxOp2="Uninstall"
                     auxOp3="uninstall"
                     auxOp4="Uninstallation"
                     auxOp5="uninstallation"
                     ;;
    "preuninstall")  auxOp1="Pre-uninstalling"
                     auxOp2="Pre-uninstall"
                     auxOp3="pre-uninstall"
                     auxOp4="Pre-uninstallation"
                     auxOp5="pre-uninstallation"
                     ;;
    "update")        auxOp1="Updating"
                     auxOp2="Update"
                     auxOp3="update"
                     auxOp4="Updating"
                     auxOp5="updating"
                     printSystemName=1
                     ;;
    "upgrade")       auxOp1="Upgrading"
                     auxOp2="Upgrade"
                     auxOp3="upgrade"
                     auxOp4="Upgrading"
                     auxOp5="upgrading"
                     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}" = "xrunner" ];
        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}" = "xrunner" ];
        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}" = "xrunner" ];
        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
    printOnce=0
    cycle=0
    currentDate=$(${DATECOMMAND} -R)
    currentTime=""

    for i in $currentDate;
    do 
      cycle=$((cycle+1))
      if [ $cycle = 5 ]; then
        currentTime+="$i"
      elif [ $cycle != 6 ]; then
        currentTime+="$i " 
      fi
    done

    printMsg "Starting $auxOp5 at: $currentTime"

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

  if [ "$printSystemName" = "1" ];
  then
    case "$system" in
      "macosx"     ) detectedSystem="Mac OS X";;
      "solaris"    ) detectedSystem="Solaris";;
      "redhat"     ) detectedSystem="Red Hat";;
      "fedora"     ) detectedSystem="Fedora";;
      "debian"     ) detectedSystem="Debian";;
      "ubuntu"     ) detectedSystem="Ubuntu";;
      "linuxmint"  ) detectedSystem="LinuxMint";;
      "elementary" ) detectedSystem="Elementary";;
      "suse"       ) detectedSystem="SUSE";;
      "slackware"  ) detectedSystem="Slackware";;
      "mandriva"   ) detectedSystem="Mandriva";;
      *            ) detectedSystem="$system";;
    esac

    if [ "$printOnce" = 0 ]; then
      printMsg "Using installation profile: $detectedSystem"
    fi
  fi

  if [ "$printOnce" = 0 ]; then
    printMsg "$auxOp4 log is: $LOGFILE"
    printOnce=1
  fi

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

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

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
    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 [[ "x${operation}" = "xuninstall" ]];
    then
      if [ $rpmVersionFirst -eq 4 ];
      then
        if [ $rpmVersionSecond -eq 8 ] || [ $rpmVersionSecond -gt 8 ];
        then
          ${MKDIRCOMMAND} -p /etc/NX/
          ${MKDIRCOMMAND} -p "$NX_ROOT"
          ${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/nxrunner.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/web.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

            ${MKDIRCOMMAND} -p /etc/NX/server/
            ${MKDIRCOMMAND} -p /etc/NX/server/localhost
            ${MKDIRCOMMAND} -p /etc/NX/server/packages
            ${TOUCHCOMMAND} /etc/NX/server/packages/nxplayer.tar.gz
            ${TOUCHCOMMAND} /etc/NX/server/packages/nxrunner.tar.gz
            ${TOUCHCOMMAND} /etc/NX/server/localhost/server.cfg.sample
            ${TOUCHCOMMAND} /etc/NX/server/packages/nxserver.tar.gz
            ${TOUCHCOMMAND} /etc/NX/server/packages/nxnode.tar.gz
            
	  fi
	fi
      fi
    elif [[ "x${operation}" = "xupdate" ]];
    then
      if [ "${major_version}" -le 7 ];
      then
        if [ ! -d /etc/NX/server/packages ]
	then
          ${MKDIRCOMMAND} -p /etc/NX/server/packages/
	fi

        ${TOUCHCOMMAND} /etc/NX/server/packages/nxclient.tar.gz
      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="Installation"
                     ;;
    "install-basic") auxProcess="Installation"
                     operation2="installation"
                     ;;
    "uninstall")     auxProcess="Uninstallation"
                     ;;
    "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${SHOWAUDIOINFO}" = "xyes" ];
    then

      #
      # Lack of PulseaAudio is not an error.
      #

      SHOWWARNINFO="no"

      if [ -f "${NX_ROOT}/share/documents/${PACKAGE_NAME}/audio-info" ];
      then
        printMsgNoDot "Displaying file: ${NX_ROOT}/share/documents/${PACKAGE_NAME}/audio-info"
        ${CATCOMMAND} "${NX_ROOT}/share/documents/${PACKAGE_NAME}/audio-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}" = "xrunner" ];
      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}" = "xrunner" ];
      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}" = "xrunner" ];
      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

    currentDate=$(${DATECOMMAND} -R)
    cycle=0
    currentTime=""

    for i in $currentDate;
    do 
      cycle=$((cycle+1))
      if [ $cycle = 5 ]; then
        currentTime+="$i"
      elif [ $cycle != 6 ]; then
        currentTime+="$i " 
      fi
    done

    getInstallationStatus

    if [ "x${ret_getInstallationStatus}" = "x1" ];
    then
      printMsg "${auxProcess} completed with errors at: ${currentTime}"
    elif [ "x${ret_getInstallationStatus}" = "x2" ];
    then
      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 [ $("${ECHOCOMMAND}" "x${PACKAGE_FILE}" | "${GREPCOMMAND}" -s "\-cluster") ] && [ "x${operation}" = "xinstall" ]
      then
        printClusterInfo
      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/server.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."
    ${ECHOCOMMAND}
    ${ECHOCOMMAND} "--fixcuda                   Run the CUDA initialization procedure."
  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;;
      "--fixcuda"                )  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;;
      "--networksetup"  ) action_ok=1
                          generation="$par2"
                          return;;
    esac

  elif [ "${PACKAGE_NAME}" = "network-database" ];
  then
    case "$action" in
      "--upgrade"        ) needSystem=0
                           action_ok=1
                           return;;
      "--remove-base"    ) needSystem=0
                           removebaseParm="$par2"
                           action_ok=1
                           return;;
      "--remove-all"     ) needSystem=0
                           removeallParm="$par2"
                           action_ok=1
                           return;;
      "--backup"         ) needSystem=0
                           backupdatabaseParm="$par2"
                           action_ok=1
                           return;;
      "--shutdown"       ) needSystem=0
                           action_ok=1
                           return;;
    esac

  elif [ "${PACKAGE_NAME}" = "network-gateway" ];
  then
    case "$action" in
      "--upgrade"        ) needSystem=0
                           action_ok=1
                           return;;
      "--remove-base"    ) needSystem=0
                           removebaseParm="$par2"
                           action_ok=1
                           return;;
      "--remove-all"     ) needSystem=0
                           removeallParm="$par2"
                           action_ok=1
                           return;;
      "--backup"         ) needSystem=0
                           action_ok=1
                           return;;
      "--shutdown"       ) needSystem=0
                           action_ok=1
                           return;;
    esac

  elif [ "${PACKAGE_NAME}" = "network-messaging" ];
  then
    case "$action" in
      "--upgrade"        ) needSystem=0
                           action_ok=1
                           return;;
      "--remove-base"    ) needSystem=0
                           removebaseParm="$par2"
                           action_ok=1
                           return;;
      "--remove-all"     ) needSystem=0
                           removeallParm="$par2"
                           action_ok=1
                           return;;
      "--backup"         ) needSystem=0
                           backupnodeParam="$par2"
                           action_ok=1
                           return;;
      "--shutdown"       ) needSystem=0
                           action_ok=1
                           return;;
    esac

  elif [ "${PACKAGE_NAME}" = "network-relay" ];
  then
    case "$action" in
      "--upgrade"        ) needSystem=0
                           action_ok=1
                           return;;
      "--remove-base"    ) needSystem=0
                           removebaseParm="$par2"
                           action_ok=1
                           return;;
      "--remove-all"     ) needSystem=0
                           removeallParm="$par2"
                           action_ok=1
                           return;;
      "--backup"         ) needSystem=0
                           action_ok=1
                           return;;
      "--shutdown"       ) needSystem=0
                           action_ok=1
                           return;;
    esac

  elif [ "${PACKAGE_NAME}" = "network-web" ];
  then
    case "$action" in
      "--remove-base"    ) needSystem=0
                           removebaseParm="$par2"
                           action_ok=1
                           return;;
      "--remove-all"     ) needSystem=0
                           removeallParm="$par2"
                           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"             ) ;;
      "ubuntu"             ) ;;
      "linuxmint"          ) ;;
      "elementary"         ) ;;
      "arch"               ) ;;
      "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
    getPreviousVersion

    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" 2>/dev/null | \
                        "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | \
                        "${SEDCOMMAND}" -nre \
                         's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')

    if [ "x$ret_DistroVersion" = "x" ];
    then
      ret_DistroVersion="0.0.0" #for Arch Linux
    fi

  elif [ -r "/usr/bin/lsb_release" ] && [ "x${system}" = "xubuntu" ];
  then
    ret_DistroVersion=$($LSBRELEASECOMMAND -r | ${AWKCOMMAND} '{print $2}')
  elif [ -r "/etc/lsb-release" ] && [ "x${system}" != "xredhat" ];
  then
    ret_DistroVersion=$("${GREPCOMMAND}" "VERSION" "/etc/lsb-release" 2>/dev/null | \
                        "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | \
                        "${SEDCOMMAND}" -nre \
                         's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')
  elif [ -r "${DISTRO_FILE}" ] && [ "x$system" != "xubuntu" ] && \
       [ "x$system" != "xlinuxmint" ] && [ "x$system" != "xelementary" ];
  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] == "NXRUNNER") {
          tab[i] = "NXRunner"
        } 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" "cmd"

  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" "cmd"
    if [ -f "$CONFIG_FILE.update" ];
    then
      sourceFile="$CONFIG_FILE.update"
    else
      case "$system" in
        "ubuntu"     ) syscfg="debian";;
        "linuxmint"  ) syscfg="debian";;
        "elementary" ) syscfg="debian";;
        *            ) syscfg="$system";;
      esac
      
      if [ -f "$NX_ROOT/etc/${PACKAGE_NAME}-$syscfg.cfg.sample" ];
      then
        sourceFile="$NX_ROOT/etc/${PACKAGE_NAME}-$syscfg.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 "775" "${NX_VAR_DIR}/log" "warn"
  fi
}

resetNXConfig ()
{

  if [ -f "$CONFIG_FILE" ];
  then
    printMsg "Saving configuration file to: $CONFIG_FILE.backup" "cmd"
    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
    runCommand "'/etc/NX/nx${PACKAGE_NAME}' --validate" "Cannot validate license file" "error"
  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" "cmd"

  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"

  grep_out="$("$GREPCOMMAND" "$CFG_OPTION" "$CONFIG_FILE")"
  grep_out2="$("$GREPCOMMAND" "$FIRST_LINE_OPTION" "$CONFIG_FILE")"
  
  if [ "x$grep_out" != "x" ] && [ "x$grep_out2" != "x" ];
  then
  
    "$SEDCOMMAND" '/'"$FIRST_LINE_OPTION"'/,/'"$CFG_OPTION"'/ {

                  /'"$FIRST_LINE_OPTION"'/ {
                                             x
                                             d
                                           }

                  /^ *#* *'"$CFG_OPTION"'/ {
                                             x
                                             d
                                           }

                                        H

                                        $ {
                                            x
                                            p
                                            d
                                          }

                                        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"

  fi

  printMsgRemoveKeyFromConfigFile "${CFG_OPTION}"
}

removeOptionFromCfgExtended()
{

  FIRST_LINE="$1"
  SECOND_LINE="$2"
  LAST_LINE="$3"
    
  "$AWKCOMMAND" -v F_LN="$FIRST_LINE" -v S_LN="$SECOND_LINE" -v L_LN="$LAST_LINE" '{
    line1 = $0;
    if (line1 == F_LN)
    {
      if (getline > 0)
      {
        line2 = $0;
        if (line2 == S_LN)
        {
          f = 1;
        }
        else
        {
          print line1;
        }
      }
    }
    if (line1 == L_LN)
    {
      getline;
      f = 0;
    }
  } !f' "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  "$SEDCOMMAND" -e '/^#$/{ N; /^#\n$/d;}' "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"
}

insertKeytoConfigFile ()
{
  key="${1}"
  key_description="${2}"
  insert_after="${3}"

  #
  # Adding keys to localhost/server.cfg when 4th param is given.
  #

  overwrite_cfg="${4}"

  if [ "${overwrite_cfg}x" = "x" ]
  then
    config_file="${CONFIG_FILE}"
  else
    config_file="${overwrite_cfg}"
  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

  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"

    ${PRINTFCOMMAND} "${key_description}" >> "${config_file}"
  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
  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

    if [ "x$PACKAGE_NAME" != "xplayer" ] || [ ! -f "$NXSHELL" ];
    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"
    fi
  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

  adaptDesktopFiles

  runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine${menu_suffix}-base.desktop' '${NX_XDG}/NoMachine${menu_suffix}-base-unity.desktop'" "Cannot install menu '${NX_XDG}/NoMachine${menu_suffix}-unity.desktop'" "cmd"

  runCommand "${XDGDESKTOPMENUCOMMAND} install --mode system '${NX_XDG}/NoMachine${menu_suffix}-base-xfce.desktop'" "Cannot install menu '${NX_XDG}/NoMachine${menu_suffix}-xfce.desktop'" "cmd"

  return 0
}

removeObsoleteXDGMenu ()
{
  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 obsolete XDG Menu" "cmd"

  if [ "x${PACKAGE_NAME}" = "xserver" ];
  then
    runCommand "${XDGDESKTOPMENUCOMMAND} uninstall --mode system  \
                NoMachine${menu_suffix}-dir.directory \
                NoMachine${menu_suffix}-status.desktop \
                NoMachine${menu_suffix}-status-unity.desktop \
                NoMachine${menu_suffix}-status-xfce.desktop" \
               "Cannot uninstall server status menu" "cmd"
  else
    runCommand "${XDGDESKTOPMENUCOMMAND} uninstall --mode system \
                NoMachine${menu_suffix}-dir.directory" "Cannot uninstall menu \
                'NoMachine${menu_suffix}-dir.directory'" "cmd"
  fi
}

removeXDGMenuFile ()
{
  xdgFileName="$1"
  if [ -z "$XDG_DATA_DIRS" ] || [ "$XDG_DATA_DIRS" = ":" ] 
  then
    xdgDataDirs="/usr/share/ubuntu/:/usr/share/xubuntu/:/usr/share/gnome/:/usr/share/xfce4:/usr/share/mate:/usr/share:/var/lib/snapd/desktop:/usr/local/share"
  else
    xdgDataDirs="$XDG_DATA_DIRS:/usr/share/ubuntu/:/usr/share/xubuntu/:/usr/share/gnome/:/usr/share/xfce4:/usr/share/mate:/usr/share:/var/lib/snapd/desktop:/usr/local/share"
  fi

  IFS=: read -r -d '' -a path_array < <(printf '%s:\0' "$xdgDataDirs")

  for xdgPath in "${path_array[@]}"
  do
    commandRmIfExist "$xdgPath/applications/$xdgFileName" "warn"
  done
}

removeObsoleteMenuFiles ()
{
  printMsg "Removing obsolete menu applications entries" "cmd"

  if [ "x${PACKAGE_NAME}" = "xserver" ];
  then
    commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-status.desktop" "warn"
    removeXDGMenuFile "NoMachine${menu_suffix}-status.desktop"
    
    commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-status-unity.desktop" "warn"
    removeXDGMenuFile "NoMachine${menu_suffix}-status-unity.desktop"
    
    commandRmIfExist "${APPLICATIONS_DIR}/NoMachine${menu_suffix}-status-xfce.desktop" "warn"
    removeXDGMenuFile "NoMachine${menu_suffix}-status-xfce.desktop"
  fi

  commandRmIfExist "${DESKTOPDIRS_DIR}/NoMachine${menu_suffix}-dir.directory" "warn"

  commandRmIfExist "${APPLICATIONSMERGED_DIR}/NoMachine${menu_suffix}-dir.menu" "warn"

}

removeObsoleteMenuApplications ()
{
  getPreviousVersion

  setMenuVariables
  
  if [ "${major_version}" -le 8 ];
  then
    removeObsoleteXDGMenu

    removeObsoleteMenuFiles
  fi
}

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 [ -f "${XDG_CONFIG_DIRS}/menus/applications-merged/${menuFile}" ]
  then
    menuFullNameFile="${XDG_CONFIG_DIRS}/menus/applications-merged/${menuFile}"

  elif [ -f "/etc/xdg/menus/applications-merged/${menuFile}" ]
  then
    menuFullNameFile="/etc/xdg/menus/applications-merged/${menuFile}"

  else
    menuFullNameFile=""
    ret_updateXDGMenuFile=1

    printMsg "XDG menu was not updated" "cmd"

    return 0
  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
    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

  if [ "x$anywhere" = "x0" ];
  then
    updateXDGMenuFile "NoMachine${menu_suffix}-dir.menu"
  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 ()
{
  #
  # Function only for MacOS.
  #

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

  user=$1

  ret_hideMacUser=0
  getMacOSXVersion

  if [ ${ret_getMacOSXVersion} -ne 0 ];
  then
    ret_hideMacUser=1
    return 0
  fi

  #
  # First check if user is already hidden.
  #

  is_user_already_hidden=""
  is_user_already_hidden=$(defaults read /Library/Preferences/com.apple.loginwindow HiddenUsersList | ${GREPCOMMAND} "${user}")

  if [[ "x${is_user_already_hidden}" = "x" ]]
  then
    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
  else

    #
    # User is already hidden.
    #

    printMsg "User $user is already hidden" "cmd"
  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
}

foundUpstartDirectory ()
{
  if [ -d "/etc/init/" ]
  then
    UPSTART_DIRECTORY="/etc/init/"
  else
    UPSTART_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

    if [ "${ret_isSystemDSupported}" = 0 ]
    then
      result="$(ps -p1 | ${GREPCOMMAND} systemd 2>/dev/null)"

      if [ "x${result}" != "x" ];
      then
        ret_isSystemDSupported=1

        return 0
      fi
    fi
  fi

  return 0
}

isUpstartSupported ()
{
  ret_isUpstartSupported=0

  foundUpstartDirectory

  if [ -x "${INITCTLCOMMAND}" ] && [ "x${UPSTART_DIRECTORY}" != "x" ];
  then
    if [ -f /proc/1/exe ];
    then
      result=$(${READLINKCOMMAND} /proc/1/exe | ${GREPCOMMAND} init 2>/dev/null)

      if [ "x${result}" != "x" ];
      then
        ret_isUpstartSupported=1

        return 0
      fi
    fi

    if [ "${ret_isUpstartSupported}" = 0 ]
    then
      result="$(ps -p1 | ${GREPCOMMAND} init 2>/dev/null)"

      if [ "x${result}" != "x" ];
      then
        ret_isUpstartSupported=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"

  if [ -d /run/systemd ];
  then
    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
  fi
}

stopSystemDService ()
{
  if [ -d /run/systemd ];
  then
    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
  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

  if [ -f "${NX_ROOT}/bin/nxfsm-legacy" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "555" "${NX_ROOT}/bin/nxfsm-legacy" "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
}

chooseKext ()
{
  choose_kext="${1}"
  ret_chooseKext=""

  systemVersion=$(${SWVERSCOMMAND} | ${GREPCOMMAND} "ProductVersion:" | \
                 ${GREPCOMMAND} -o "[0-9]*\..*")

  getMacOSXVersion

  if [[ "$systemVersion" == 10.5* || "$systemVersion" == 10.6* || "$systemVersion" == 10.7* ]];
  then

    printMsg "Choosed legacy ${choose_kext} kext" "cmd"

    ret_chooseKext="${NX_ROOT}/bin/drivers/${choose_kext}.kext-legacy"

  elif [[ "${mac_ver_major}" -ge 11 ]] && [ "x${choose_kext}" = x"nxaudio" ]
  then

    #
    # Since MacOS 11 nxaudio.kext is replaced with NMAudio.driver and NMAudioMic.driver.
    #

    printMsg "Choosed NMAudio and NMAudioMic drivers" "cmd"

  else

    printMsg "Choosed ${choose_kext} kext" "cmd"

    ret_chooseKext="${NX_ROOT}/bin/drivers/${choose_kext}.kext"
  fi
}

copyAndUnsignKext ()
{
  kext_destination="${1}"
  kext_path="${2}"

  binary_name="${3}"
 
  if [ -f "${NX_ROOT}/bin/nxsign" ]
  then
    "${CPCOMMAND}" -a  "${kext_path}" "${kext_path}.unsigned"
    "${RMCOMMAND}" -rf "${kext_path}.unsigned/Contents/_Code"*

    "${NX_ROOT}/bin/nxsign" "${kext_path}.unsigned/Contents/MacOS/${binary_name}"

    if [ -f "${kext_path}.unsigned/Contents/MacOS/${binary_name}.unsigned" ]
    then
      "${RMCOMMAND}" "${kext_path}.unsigned/Contents/MacOS/${binary_name}"
      "${MVCOMMAND}" "${kext_path}.unsigned/Contents/MacOS/${binary_name}.unsigned" \
                     "${kext_path}.unsigned/Contents/MacOS/${binary_name}"

      "${MVCOMMAND}" "${kext_path}.unsigned" "${kext_destination}/${binary_name}.unsigned.kext"

      "${COMMANDKEXTLOAD}" "${kext_destination}/${binary_name}.unsigned.kext"
    else
      printMsg "Unsigning kext ${binary_name} has failed." "onlylog"
    fi
  else
    printMsg "Tool nxsign not found." "onlylog"
  fi
}

setLegacyKexts ()
{
  #
  # This function is used for loading unsign kexts on legacy MacOSX 10.7.
  #  https://developer.apple.com/library/archive/releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_9.html#//apple_ref/doc/uid/TP40013207-CH100
  #  ..unsigned copy in /System/Library/Extensions, in addition to any signed copy in /Library/Extensions.
  #

  if [ "${system}" = "macosx" ];
  then
    systemVersion=$(${SWVERSCOMMAND} | ${GREPCOMMAND} "ProductVersion:" | \
                   ${GREPCOMMAND} -o "[0-9]*\..*")

    if [[ "${systemVersion}" = "10.7"* ]];
    then
      k_path="${NX_ROOT}/bin/drivers/"
      d_path="/System/Library/Extensions/"

      usb_path="${k_path}/nxusb-legacy_10.7.kext"
      fs_path="${k_path}/nxfuse.kext" # nxfuse legacy kext is no longer supported
      audio_path="${k_path}/nxaudio.kext-legacy"

      copyAndUnsignKext "${d_path}" "${usb_path}"   "nxusb-legacy_10.7"
      copyAndUnsignKext "${d_path}" "${fs_path}"    "nxfuse"
      copyAndUnsignKext "${d_path}" "${audio_path}" "nxaudio"
    fi
  fi
}

removeKextTemproraryFiles ()
{
  destination="${1}"

  list=""

  list=$(${FINDCOMMAND} "${destination}" -name *".temprorary")

  if [ "${list}x" != "x" ]
  then
    for file in ${list}
    do
      ${RMCOMMAND} -rf "${file}"
    done
  fi
}

setupKext ()
{

  #
  # This function os used only for nxaudio installation.
  #

  operation="${1}"
  kext_name="${2}"

  LIBRARYEXTENSIONS="/System/Library/Extensions/"

  getMacOSXVersion

  if [ "x$ret_getMacOSXVersion" = "x0" ];
  then
    
    compareVersions "$mac_ver_full" "10.15"

    if [ "x$ret_compareVersions" != "x2" ];
    then
      LIBRARYEXTENSIONS="/Library/Extensions/"
    fi

  fi

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

    chooseKext "nxaudio"

    install_kext=1
    replace_kext=0

    if [ "x${operation}" = "xupdate" ] && [[ "${mac_ver_major}" -lt 11 ]] 
    then

      old_kext_version=""
      new_kext_version=""

      if [ -r "${LIBRARYEXTENSIONS}/${kext_name}.kext/Contents/Info.plist" ];
      then
        old_kext_version=$("${MD5SUMCOMMAND}" -q "${LIBRARYEXTENSIONS}/${kext_name}.kext/Contents/MacOS/${kext_name}")
      fi

      if [ -r "${ret_chooseKext}/Contents/Info.plist" ];
      then
        new_kext_version=$("${MD5SUMCOMMAND}" -q "${ret_chooseKext}/Contents/MacOS/${kext_name}")
      fi

      if [ "x${old_kext_version}" = "x${new_kext_version}" ];
      then
        printMsg "No need to update nxaudio.kext" "cmd"

        install_kext=0
      else
        printMsg "Updating nxaudio.kext" "cmd"
      fi

    elif [ "x${operation}" = "xupdate" ] && [[ "${mac_ver_major}" -ge 11 ]]
    then

      #
      # Since MacOS 11 nxaudio.kext is replaced with NMAudio.driver and NMAudioMic.driver.
      #

      printMsg "Setting nxaudio.kext to replace with NMAudio and NMAudioMic drivers" "cmd"

      replace_kext=1
    fi

    if [ -f "${NX_ROOT}/bin/drivers/temporary" ]
    then

      #
      # Due to problem in 6.10.12
      #  we need to force loading kext after removing .temporary files.
      #

      install_kext=1

      #
      # Removing file flag created in nxrunner setup.
      #

      "${RMCOMMAND}" "${NX_ROOT}/bin/drivers/temporary"
    fi

    if [ ${install_kext} -eq 1 ];
    then

      if [ "${kext_name}x" = "nxaudiox" ]
      then
        changeKeyAtConfigFile "${CONFIG_FILE}" "AudioInterface" "nxaudio"
      fi

      if [ -d "${LIBRARYEXTENSIONS}/${kext_name}.kext" ];
      then
        commandRmDirRecursively "${LIBRARYEXTENSIONS}/${kext_name}.kext" "cmd"

        if [ "${kext_name}"x = "nxaudiox" ]
        then
          kextunload -v 6 -b com.nomachine.driver.nxau
        fi
      fi

      if [ ${replace_kext} -eq 1 ] || [[ "${mac_ver_major}" -ge 11 ]];
      then

        #
        # Since MacOS 11 nxaudio.kext is replaced with NMAudio.driver and NMAudioMic.driver.
        #

        if [ ! -d /Library/Audio/Plug-Ins/HAL/ ]
        then
          ${MKDIRCOMMAND} -p /Library/Audio/Plug-Ins/HAL/
        fi

        if [ -f /Library/Audio/Plug-Ins/HAL/NMAudio.driver ]
        then
          ${RMCOMMAND} /Library/Audio/Plug-Ins/HAL/NMAudio.driver
        fi

        if [ -f /Library/Audio/Plug-Ins/HAL/NMAudioMic.driver ]
        then
          ${RMCOMMAND} /Library/Audio/Plug-Ins/HAL/NMAudioMic.driver
        fi

        kextcache -prune-staging

        printMsg "Copying NMAudio and NMAudioMic drivers" "cmd"

        $CPCOMMAND -a /Applications/NoMachine.app/Contents/Frameworks/bin/drivers/NMAudio.driver    /Library/Audio/Plug-Ins/HAL/NMAudio.driver
        $CPCOMMAND -a /Applications/NoMachine.app/Contents/Frameworks/bin/drivers/NMAudioMic.driver /Library/Audio/Plug-Ins/HAL/NMAudioMic.driver

        commandChmodR 755 /Library/Audio/Plug-Ins/HAL/NMAudio*
        commandChownR "root:${ROOTGNAME}" /Library/Audio/Plug-Ins/HAL/NMAudio*

        commandChmod 644 /Library/Audio/Plug-Ins/HAL/NMAudio.driver/Contents/Resources/data.txt
        commandChmod 644 /Library/Audio/Plug-Ins/HAL/NMAudioMic.driver/Contents/Resources/data.txt

        if [ ${mac_ver_major} -gt 14 ] || ([ ${mac_ver_major} -eq 14 ] && [ ${mac_ver_minor} -ge 4])
        then
          ${KILLALLCOMMAND} coreaudiod
          ${LAUNCHCTLCOMMAND} start com.apple.audio.coreaudiod 
        else
          ${LAUNCHCTLCOMMAND} stop com.apple.audio.coreaudiod
          ${LAUNCHCTLCOMMAND} start com.apple.audio.coreaudiod
        fi
      else

        printMsg "Installing ${kext_name}.kext" "cmd"

        commandCpDir "${ret_chooseKext}" "${LIBRARYEXTENSIONS}/${kext_name}.kext"

        commandChmodR "755" "${LIBRARYEXTENSIONS}/${kext_name}.kext"

        commandChownR "root:${ROOTGNAME}" "${LIBRARYEXTENSIONS}/${kext_name}.kext"

        removeKextTemproraryFiles "${LIBRARYEXTENSIONS}/${kext_name}.kext/"

        if [ -a "/sbin/kextload" ];
        then
          COMMANDKEXTLOAD="/sbin/kextload"
        else
          COMMANDKEXTLOAD="kextload"
        fi

        runCommand "${COMMANDKEXTLOAD} ${LIBRARYEXTENSIONS}/${kext_name}.kext" "Cannot load: ${kext_name}"

      fi
    fi
  fi
}

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}" != "runner" ] && [ "${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}" != "runner" ] && [ "${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 "${NXPRINT}" ];
    then
      printMsg "Cannot find file: ${NXPRINT}" "warn"
      ret_nxPrintSetup=1
      return 0
    fi
  fi

  if [ "x$system" = "xmacosx" ] && [ "${PACKAGE_NAME}" != "runner" ];
  then
    commandMkDir "/Library/Application Support/NoMachine/var/tmp/nxprint"
    commandChownChmod "${NX_GROUP}:${LPADMIN}" "0770" "/Library/Application Support/NoMachine/var/tmp/nxprint"
  fi

  getCupsBackend

  if [ "x${CUPS_BACKEND}" != "x" ];
  then
    if [ "${PACKAGE_NAME}" = "node" ];
    then
      if [ -x "${CUPS_BACKEND}/nx" ];
      then
        SHOWCUPSINFO="no"
      fi

      commandInstall "root" "${ROOTGNAME}" "755" "${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
          commandInstall "root" "${ROOTGNAME}" "755" "/usr/lib/cups/backend/nx" "Cannot install nx cups backend in directory: /usr/lib/cups/backend" "cmd"
        fi
      fi

    else

      if [ -x "${CUPS_BACKEND}/nxprint" ];
      then
        SHOWCUPSINFO="no"
      fi

      ${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
          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
}

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}"

  license_1="${3}"
  license_2="${4}"

  product_1=""
  product_2=""

  product_1=$(${GREPCOMMAND} "Product:" "${license_1}")
  product_2=$(${GREPCOMMAND} "Product:" "${license_2}")

  if [[ "${product_1}x" = *"Premium Subscription"* ]] || \
     [ "${acronym_1}x" = "LEDSSx" ] || [ "${acronym_1}x" = "LEDSEx" ] || \
     [ "${acronym_1}x" = "MEDSSx" ] || [ "${acronym_1}x" = "MEDSEx" ] || \
     [ "${acronym_1}x" = "REDSSx" ] || [ "${acronym_1}x" = "REDSEx" ]
  then
    acronym_1=$(${ECHOCOMMAND} "${acronym_1}" | ${SEDCOMMAND} s'/..$//')
  else
    acronym_1=$(${ECHOCOMMAND} "${acronym_1}" | ${SEDCOMMAND} s'/.$//')
  fi

  if [[ "${product_2}x" = *"Premium Subscription"* ]] || \
     [ "${acronym_2}x" = "LEDSSx" ] || [ "${acronym_2}x" = "LEDSEx" ] || \
     [ "${acronym_2}x" = "MEDSSx" ] || [ "${acronym_2}x" = "MEDSEx" ] || \
     [ "${acronym_2}x" = "REDSSx" ] || [ "${acronym_2}x" = "REDSEx" ]
  then
    acronym_2=$(${ECHOCOMMAND} "${acronym_2}" | ${SEDCOMMAND} s'/..$//')
  else
    acronym_2=$(${ECHOCOMMAND} "${acronym_2}" | ${SEDCOMMAND} s'/.$//')
  fi

  #
  # Due to the change of first acronim letter in ARM packages licenses
  #  we are replacing first letter in installed license variable to match
  #  them during update.
  #

  if [ "${acronym_1:0:1}x" = "Rx" ] && [ "${acronym_2:0:1}x" = "Lx" ]
  then
    acronym_2=$("${ECHOCOMMAND}" "${acronym_2}" | "${SEDCOMMAND}" 's/^L/R/g')

  elif [ "${acronym_1:0:1}x" = "Lx" ] && [ "${acronym_2:0:1}x" = "Rx" ]
  then
    acronym_1=$("${ECHOCOMMAND}" "${acronym_1}" | "${SEDCOMMAND}" 's/^L/R/g')
  fi

  #
  # In v9 Workstation acronym has changed from W to WS.
  #

  if [ "${acronym_1}x" = "LWx" ] && [ ${major_version} -eq 8 ]
  then
    acronym_1="LWS"
  fi

  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
  else

    if ([ "${acronym_1}" = "LSBCS" ] && [ "${acronym_2}" = "LWCS" ] && [ ${major_version} -eq 8 ]) ||\
       ([ "${acronym_1}" = "MSBCS" ] && [ "${acronym_2}" = "MWCS" ] && [ ${major_version} -eq 8 ])
    then

      #
      # Disable replacing license file while updating
      # Small Business Cloud Server by Workstation Cloud Server.
      #

      printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"

      ret_comparePackages=0

    elif [ "${acronym_1}" = "LCS" ] && [ "${acronym_2}" = "LETS" ]
    then

      #
      # Disable replacing license file while updating
      # Cloud Server by Enterprise Terminal Server.
      #

      printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"

      ret_comparePackages=0

    elif [ "${acronym_1}" = "LES" ] && [ "${acronym_2}" = "LETS" ]
    then

      #
      # Disable replacing license file while updating
      # Enterprise Server by Enterprise Terminal Server.
      #
		  
      printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"

      ret_comparePackages=0

    elif [ "${acronym_1}" = "LES" ] && [ "${acronym_2}" = "LCS" ]
    then

      #
      # Disable replacing license file while updating
      # Enterprise Server by Cloud Server.
      #
		  
      printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"

      ret_comparePackages=0

    elif (([ "${acronym_1}" = "LCS" ] && [ "${acronym_2}" = "LECS" ])  || ([ "${acronym_1}" = "MCS" ] && [ "${acronym_2}" = "MECS" ])   ||\
          ([ "${acronym_1}" = "LCS" ] && [ "${acronym_2}" = "LECSC" ]) || ([ "${acronym_1}" = "MCS" ] && [ "${acronym_2}" = "MECSC" ])  ||\
          ([ "${acronym_1}" = "LCS" ] && [ "${acronym_2}" = "LSBCS" ]) || ([ "${acronym_1}" = "MCS" ] && [ "${acronym_2}" = "MSBCS" ])) &&\
	  [ ${major_version} -eq 7 ]
    then

      #
      # Linux and MacOSX
      #  Disable replacing license file while updating
      #  Cloud Server by Enterprise Cloud Server/Enterprise Cloud Server Cluster/Small Business Cloud Server
      #

      printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"

      ret_comparePackages=0

    elif [ "${acronym_1}" = "LTSN" ] && [ "${acronym_2}" = "LETSN" ]
    then

      #
      # Disable replacing license file while updating
      # Terminal Server Node by Enterprise Terminal Server Node.
      #

      printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"

      ret_comparePackages=0

    elif [ "${acronym_1}" = "LSBS" ] && [ "${acronym_2}" = "LSBTS" ]
    then

      #
      # Disable replacing license file while updating
      # Small Business Server by Small Business Terminal Server.
      #

      printMsg "comparePackages: $acronym_1 and $acronym_2 belongs to the same product" "cmd"

      ret_comparePackages=0
    fi
  fi
}

isInstalledHtd ()
{
  if [ "x${INSTALL_HTD}" = "x" ];
  then

    INSTALL_HTD=0

    if [ -f "${NX_ROOT}/bin/nxhtd.bin" ];
    then

      if [ -f "${HTD_USR_CONFIG_FILE}" ] || [ -f "${HTD_USR_CONFIG_FILE}".sample ] || \
         [ -f "${HTD_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
    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=""

  if [ "x$system" = "xmacosx" ];
  then
    runCommand "${DSCLCOMMAND} . -read /Groups/$1" "no entry in Directory Service databease for group $1" "cmd"
    if [ "x${ret_runCommand}" = "x0" ];
    then
      ret_checkGroupExist=1
    fi
  else
    ret_checkGroupExist=$(${GREPCOMMAND} "^$1:" /etc/group 2>/dev/null)
  fi

  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" ] && [ "x${system}" != "xubuntu" ] && \
     [ "x${system}" != "xlinuxmint" ] && [ "x${system}" != "xelementary" ];
  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
}

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}"
}

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 uninstall.log file.
  #

  commandRmDirRecursively "${NX_VAR_DIR}/log/nxnode"
  commandRmDirRecursively "${NX_VAR_DIR}/log/nxserver"

  commandRmIfExist "${NX_VAR_DIR}/log/daemon.log"
  commandRmIfExist "${NX_VAR_DIR}/log/daemon.pid"
  commandRmIfExist "${NX_VAR_DIR}/log/error.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxhtd-access.log"
  commandRmIfExist "${NX_VAR_DIR}/log/nxhtd-error.log"
  commandRmIfExist "${NX_VAR_DIR}/log/install.log"
  commandRmIfExist "${NX_VAR_DIR}/log/update.log"
  commandRmIfExist "${NX_VAR_DIR}/log/server.log"
  commandRmIfExist "${NX_VAR_DIR}/log/webclient.log"
  commandRmIfExist "${NX_VAR_DIR}/log/webrunner.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
    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
    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
    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}')
    addPAMFileToArray "${INCLUDE_PAM_FILE}"
  elif [[ "${line_wheel}" =~ ^[[:space:]]*auth[[:space:]]*include ]];
  then
    INCLUDE_PAM_FILE=$(${ECHOCOMMAND} $line_wheel | ${AWKCOMMAND} '{print $3}')
    addPAMFileToArray "${INCLUDE_PAM_FILE}"
  elif [[ "${line_wheel}" =~ service= ]];
  then
    INCLUDE_PAM_FILE=$(${ECHOCOMMAND} $line_wheel | ${AWKCOMMAND} -F "service=" '{print $2}' | ${AWKCOMMAND} '{print $1}')
    addPAMFileToArray "${INCLUDE_PAM_FILE}"
  fi
}

checkPAMLine ()
{
  pamLine=$1

  checkRequiredPAMWheel "${pamLine}"

  checkSufficientPAMWheel "${pamLine}"

  getIncludeFile "${pamLine}"
}

readPAMFile ()
{
  pamFile=$1
  if [ "x$pamFile" = "x/etc/pam.d/su" ] && [ ! -f "$pamFile" ];
  then
    pamFile="/usr/etc/pam.d/su"
  fi

  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
}

mergeCloudCfgDefaults ()
{
  check_key=$(${GREPCOMMAND} "ApacheUname" ${CONFIG_FILE} 2>/dev/null)

  if [[ "${check_key}x" = "x" ]]
  then

    ${ECHOCOMMAND} "#
# Set the log level of NoMachine Web Player. Web Player logs all events
# that are <= to the level specified below, according to the following
# convention:
#
# KERN_ERR         3: Error condition.
# KERN_INFO        6: Informational.
# KERN_DEBUG       7: Debug-level messages.
#
# The suggested values are:
#
# 6: Default value. Only relevant events are logged.
#
# 7: Set the log level to debug.
#
#WebSessionLogLevel 6

#
# Specify user name of NoMachine HTTP Server owner.
#
#ApacheUname nxhtd

#
# Specify group name of NoMachine HTTP Server owner.
#
#ApacheGname nxhtd

#
# Allow NoMachine HTTP Server to serve content of Web Player applica-
# tion.
#
# 1: Enabled. Users can access the Web Player application.
#
# 0: Disabled. The Web Player application is not accessible.
#
#EnableWebPlayer 1

#
# Specify the absolute path for the Web Player graphic interface and
# for storing session images generated by the X11 agent.
#
#WebDirPath /usr/NX/share/htdocs/nxwebplayer

#
# Make Web Player request user credentials to connect to the server
# or try to connect automatically as a guest user on the server:
#
# 1: Enabled. Web Player tries to log-in to server as a guest
#    without the need for user intervention. Server must support
#    the automatic generation of guest accounts and have this
#    functionality enabled.
#
# 0: Disabled. Web Player prompts the user asking for access
#    credentials to log-in to server. Users can provide either
#    their username and password or to try to log-in as a guest
#    if the server supports it.
#
#EnableWebGuest 0

#
# Show the tutorial wizard for the menu panel at session startup.
#
# 1: Enabled. Display the tutorial screenshots.
#
# 0: Disabled. Do not show the tutorial.
#
#EnableWebMenuTutorial 1

#
# Make Web Player change connection name:
# tion.
#
# 1: Enabled. Allows to have displayed name from Section "Server"
#    directive.
#
# 0: Disabled. Allows to see hostname of the server displayed.
#
#EnableWebConnectionName 0

#
# Specify the method to be used for browser-server communication. By
# default this keys is set to 'classic'. To use WebRTC technology
# set this key to 'classic,webrtc'. In this case HTML5 real-time
# communication will be used when the browser supports WebRTC and
# will fall back to the classic web media exchange protocol in case
# of browser not supporting WebRTC.
#
#AcceptedWebMethods classic

#
# The Section directive allows to define settings for the server
# where the Web Player will connect. Edit lines below to define a
# server different from localhost. Protocol is by default 'NX' as
# well as port is '4000'. To use SSH service, specify 'system' to
# authorize with system password or 'nomachine' to authorize with
# a server RSA key. In this case NoMachine uses by default port 4022
# on Windows and 22 on the other operating systems.
#
Section "Server"

Name "Connection to localhost"
Host 127.0.0.1
Protocol NX
Port 4000

EndSection

#
# When WebRTC is enabled, set parameters for STUN/TURN utilities to
# permit NAT traversal for peer to peer direct video, audio and data
# streaming. Replace 'hostname' and 'portnumber' with the ip or host
# name of the network server; replace 'username' and 'password' with
# username and password to be used for authenticating to such server.
# If a TURN server has to be contacted, duplicate section below, set
# it to Section "TURN" and provide the appropriate values for Host,
# Port, User and Password parameters. Define multiple sections for
# different STUN or TURN servers to provide an alternative server
# in case the first of the list is not reachable.
#
# Section "STUN"
#
# Host      hostname
# Port      portnumber
# User      username
# Password  password
#
# EndSection" >> ${CONFIG_FILE}
  fi
}

setCatalinaUpper ()
{
  catalinaUpper="0"
  
  getMacOSXVersion

  compareVersions "$mac_ver_full" "10.15"

  if [ "x$ret_compareVersions" != "x2" ];
  then
    catalinaUpper="1"
  fi
}

mvPlayerScriptsShare ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    if [ -d "${NX_ROOT}/../share" ];
    then
      $CPCOMMAND -a "${NX_ROOT}/"../share/. "${NX_ROOT}/share/"
      commandRmDirRecursively "${NX_ROOT}/../share" "cmd"
    fi;

    if [ -d "${NX_ROOT}/../scripts" ];
    then
      $CPCOMMAND -a "${NX_ROOT}/"../scripts/. "${NX_ROOT}/scripts/"
      commandRmDirRecursively "${NX_ROOT}/../scripts" "cmd"
    fi;
  fi;
}

restoreDBfromBackup ()
{
  db_file="${1}"

  if [ ! -f "${db_file}" ] && [ -f "${db_file}.backup" ]
  then
    "${MVCOMMAND}" "${db_file}.backup" "${db_file}"

    if [ -f "${db_file}" ]
    then
      printMsg "Restored \"${db_file}.backup\"." "cmd"
    else
      printMsg "Restoring \"${db_file}.backup\" failed." "cmd"
    fi
  fi
}

setUpRedis ()
{
  if [ "${system}" != "macosx" ];
  then
    if [ -f "${NX_ROOT}/etc/nxdb" ]
    then
      commandMv "${NX_ROOT}/etc/nxdb" "${NX_ROOT}/var/db/server.db"
    fi

    commandChownChmod "${USER_NX}:${USER_NX}" "600" "${NX_ROOT}/var/db/server.db" "warn"
  else
    if [ -f "${NX_ROOT}/etc/nxdb" ]
    then
      commandMv "${NX_ROOT}/etc/nxdb" "${NXUSERHOME}/db/server.db"
    fi
  fi

  runCommand "'${NXSHELL}' --updatedb" "Cannot update NX database." "warn"
}

removeInstallDir ()
{
  if [[ "x${system}" = "xmandriva" ]] || [[ "x${system}" = "xfedora" ]] || [[ "x${system}" = "xredhat" ]] || [[ "x${system}" = "xsuse" ]];
  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 ] && [ $rpmVersionSecond -ge 8 ];
    then
      "$RMCOMMAND" -rf "$NX_ROOT"
      "$MKDIRCOMMAND" -p "$NX_ROOT"
    else
      "$RMCOMMAND" -rf "$NX_ROOT"
    fi
  elif [ "x${system}" != "xmacosx" ];
  then
    "$RMCOMMAND" -rf "$NX_ROOT"
  fi
}


addNXUser ()
{
  parsePAMFile

  if [ "${system}" = "macosx" ];
  then

    checkGroupExist "$NX_GROUP"
    if [ "x$ret_checkGroupExist" = "x" ];
    then
      addGroupMac "$NX_GROUP" "NX group"
    fi
    
    checkNXUserExist
    if [ "x${ret_checkNXUserExist}" = "x0" ];
    then
      addNXUserMac
    else
      hideMacUser "${USER_NX}"
    fi

    if [ "x${NX_MPKG_PACKAGE}" = "xserver" ];
    then
      runCommand "${CPCOMMAND} -Rf '${NX_ROOT}/home/${USER_NX}' '${NXUSERHOME}'" "Cannot copy the content of user ${USER_NX} home directory" "warn"
    else
      isInstalledMacPkg "server"
      if [ ${ret_isInstalledMacPkg} = 0 ];
      then
        runCommand "${CPCOMMAND} -Rf '${NX_ROOT}/home/${USER_NX}' '${NXUSERHOME}'" "Cannot copy the content of user ${USER_NX} home directory" "warn"
      fi
    fi

    commandChownR "${USER_NX}" "${NXHOME}" "warn"

    commandRmDirRecursively "${NX_ROOT}/home" "warn"

    if [ "x${REQUIRED_PAM_WHEEL}" = "x1" ];
    then
      runCommand "${DSCLCOMMAND} . append /Groups/wheel GroupMembership ${USER_NX}" "Cannot add user ${USER_NX} to group 'wheel'" "warn"
    fi

    return 0
  fi

  SECONDARY_GROUP=""

  if [ "x${REQUIRED_PAM_WHEEL}" = "x1" ];
  then
    checkGroupExist "wheel"
    if [ "x${ret_checkGroupExist}" = "x" ];
    then
      getGroupById
      if [ "x${ret_getGroupById}" = "x" ];
      then
        SECONDARY_GROUP="root"
      else
        SECONDARY_GROUP="${ret_getGroupById}"
      fi
    else
      SECONDARY_GROUP="wheel"
    fi
  fi

  checkNXUserExist
  if [ "x${ret_checkNXUserExist}" = "x0" ];
  then
    if [ "x${system}" = "xsolaris" ];
    then
      addNXUserSolaris
    else
      addUserLinux "${USER_NX}" "1"

      setSELinuxStatus
      if [ "${SELINUX_ENABLED}" = "1" ];
      then
        setSELinuxContext "shell_exec_t" "/etc/NX/nxnode"
      fi

      setPermUserNXHome
    fi
  else
    printMsg "User: ${USER_NX} already exists" "cmd"

    if [ "x${system}" != "xmacosx" ];
    then
      if [ ! -d "${NXHOME}" ];
      then
        commandMkDir "${NXHOME}"
      fi

      getUserHomeDir "${USER_NX}"
      if [ "x${NXHOME}" != "x${ret_getUserHomeDir}" ];
      then
        runCommand "${USERMODCOMMAND} -d '${NXHOME}' ${USER_NX}"\
                   "Cannot change user ${USER_NX} home directory" "warn"
      fi

      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

    commandChmod "0700" "${NXHOME}"

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

  if [ -e "${NX_ROOT}/home/${USER_NX}" ];
  then
    runCommand "${CPCOMMAND} -Rf '${NX_ROOT}/home/${USER_NX}' '${NXUSERHOME}'"\
               "Cannot copy the content of user ${USER_NX} home directory" "warn"
  fi

  commandChownR "${USER_NX}" "${NXHOME}" "warn"

  #addUserNXSSHKey

  commandRmDirRecursively "${NX_ROOT}/home" "warn"
}
LICENSE_FILE="${NX_ROOT}/etc/server.lic"
SERVER_LICENSE_FILE="${NX_ROOT}/etc/server.lic"

SMB_PATH=(/sbin /bin /usr/sbin /usr/bin /usr/local/sbin /usr/local/bin)

NXINITSH="${NX_ROOT}/scripts/restricted/nxtmpperm.sh"
NXSETKEY="${NX_ROOT}/scripts/restricted/nxkeyadd.sh"
NXUSERADDSH="${NX_ROOT}/scripts/restricted/nxuseradd.sh"
NXUSERDELSH="${NX_ROOT}/scripts/restricted/nxuserdel.sh"
NXLICENSESH="${NX_ROOT}/scripts/restricted/nxlicense.sh"
NXPRELOAD="${NX_ROOT}/scripts/env/nxpreload.sh"
NXUPDATESH="${NX_ROOT}/scripts/restricted/nxupdate.sh"
NXGETCOOKIESH="${NX_ROOT}/scripts/restricted/nxcookieget.sh"
NXDISABLEAVCSH="${NX_ROOT}/scripts/restricted/nxdisableAvc.sh"
NXGETENVIRONMENT="${NX_ROOT}/scripts/restricted/nxenvironmentget.sh"
NXPORTANDCOOKIEGET="${NX_ROOT}/scripts/restricted/nxportandcookieget.sh"
NXPORTFORWARDADD="${NX_ROOT}/scripts/restricted/nxportforwardadd.sh"
NXPORTFORWARDDEL="${NX_ROOT}/scripts/restricted/nxportforwarddel.sh"
NXKILL="${NX_ROOT}/scripts/restricted/nxkill.sh"
NXSHAREDMEMSH="${NX_ROOT}/scripts/restricted/nxsharedmem.sh"
NXAMIXERSH="${NX_ROOT}/scripts/restricted/nxamixer.sh"
NXLOGINCTL="${NX_ROOT}/scripts/restricted/nxloginctl.sh"
NXCOPYSH="${NX_ROOT}/scripts/restricted/nxcopy.sh"
NXTRUNCATESH="${NX_ROOT}/scripts/restricted/nxtruncate.sh"
NXADAPTERSSH="${NX_ROOT}/scripts/restricted/nxadapters.sh"

NXFORCELOGOUTSH="${NX_ROOT}/scripts/env/forcelogout.sh"

currentDSAKey="${NXHOME}/.ssh/default.id_dsa.pub"
originalDSAKey="${NXHOME}/.ssh/restore.id_dsa.pub"

currentRSAKey="${NXHOME}/.ssh/default.id_rsa.pub"
originalRSAKey="${NXHOME}/.ssh/restore.id_rsa.pub"

NX_AUDIO_DIR="${NX_ROOT}/share/audio"
PULSEAUDIO_CONF_DIR="/etc/pulse"
ALSA_CONFIG_FILE="/usr/share/alsa/alsa.conf"
ALSA_ETC_CONFIG_FILE="/etc/alsa/alsa.conf"

SYSTEMD_NXD_SERVICE="nxd.service"

NODE_ETC_SCRIPT="/etc/NX/nxnode"

NX_ETC_SERVER=/etc/NX/node/localhost/server.cfg
NX_ETC_PLAYER=/etc/NX/node/localhost/player.cfg

resetPermissions ()
{
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXUSERDELSH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXLICENSESH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXUPDATESH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXSETKEY}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXINITSH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXUSERADDSH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXGETCOOKIESH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXGETENVIRONMENT}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXPORTANDCOOKIEGET}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXPORTFORWARDADD}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXPORTFORWARDDEL}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXKILL}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "755" "${NXWAITLOGONSH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXSHAREDMEMSH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXAMIXERSH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXLOGINCTL}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXCOPYSH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXTRUNCATESH}"
  commandChownChmodIfExist "root:${ROOTGNAME}" "744" "${NXADAPTERSSH}"
}

isDbusAvailable ()
{
  command="${WHICHCOMMAND} dbus-launch | ${HEADCOMMAND} -1"
  DBUS_PATH=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ] || [ ! -x "${DBUS_PATH}" ];
  then
    DBUS=0
    DBUS_PATH=""
  else
    DBUS=1
  fi
}

isEnabledSensor ()
{
  ret_isEnabledSensor=0

  getValueFromCfgFile "${CONFIG_FILE}" "EnableSensor"
  if [ ${ret_getValueFromCfgFile} = 2 ];
  then
    ret_isEnabledSensor=${cfg_val}
  fi
}

checkDBusLaunch ()
{
  ret_checkDBusLaunch=""

  isDbusAvailable

  local DBUS_TOOL="$DBUS_PATH"
  local DBUS_OPTION=" --exit-with-session"

  if [ "x$DBUS_TOOL" = "x" ];
  then
    getToolPath dbus-run-session
    DBUS_TOOL="$ret_getToolPath"
    DBUS_OPTION=""
  fi

  local borderVer="";

  if [ "x$DBUS_TOOL" != "x" ];
  then
    case "$system" in
      "redhat" ) borderVer="7.0";;
      "fedora" ) borderVer="30";;
      "debian" ) borderVer="9";;
      "suse"   ) borderVer="13.2";;
      "ubuntu" ) borderVer="16.3";;
    esac

    if [ "x$borderVer" != "x" ];
    then
      getDistroVersion

      compareVersions "$ret_DistroVersion" "$borderVer"

      if [ $ret_compareVersions -lt 2 ];
      then
        ret_checkDBusLaunch="${DBUS_TOOL}${DBUS_OPTION}"
      fi
    fi
  fi
}

getDefaultGnomeCmdOld ()
{
  uburel=""
  sessiontype=""

  cmdGnomeOld=""

  #
  # Set gnome-classic or gnome-falback, if available
  #

  getGnomeCommandSessionOld

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

    return 0
  fi

  #
  # Check if gnome-session is available
  #

  if [ ! -x "${GNOME_SESSION_PATH}"  ];
  then
    return 0
  fi

  if [ "$system" = "ubuntu" ];
  then

    getUbuntuVersion

    ubuMajorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | ${CUTCOMMAND} -d '.' -f1)
    ubuMinorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | ${CUTCOMMAND} -d '.' -f2)

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

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

    if [[ ("${ubuMajorRel}" -gt "11") || ("${ubuMajorRel}" -ge "11"  &&  "${ubuMinorRel}" -ge "10") ]];
    then
      if [ -f /usr/share/gnome-session/sessions/ubuntu-2d.session ];
      then
        sessiontype="ubuntu-2d"
      elif [ -f /usr/share/gnome-session/sessions/2d-ubuntu.session ];
      then
        sessiontype="2d-ubuntu"
      else
        printMsg "Unable to find proper session type for Unity. Falling back to default" "cmd"
      fi
    fi
  fi

  if [ "x${sessiontype}" = "x" ];
  then
    if [ -x /etc/gdm/Xsession ];
    then
      cmdGnomeOld="/etc/gdm/Xsession gnome-session"
    elif [ -x /etc/X11/Xsession ];
    then
      cmdGnomeOld="/etc/X11/Xsession gnome-session"
    elif [ ${DBUS} = "1" ] && [ "x${DBUS_PATH}" != "x" ];
    then
      cmdGnomeOld="${DBUS_PATH} --exit-with-session gnome-session"
    else
      cmdGnomeOld=""
    fi
  else
    if [ -x /etc/gdm/Xsession ];
    then
      cmdGnomeOld="/etc/gdm/Xsession 'gnome-session --session=$sessiontype'"
    elif [ -x /etc/X11/Xsession ];
    then
      cmdGnomeOld="/etc/X11/Xsession 'gnome-session --session=$sessiontype'"
    elif [ ${DBUS} = "1" ] && [ "x${DBUS_PATH}" != "x" ];
    then
      cmdGnomeOld="${DBUS_PATH} --exit-with-session gnome-session --session=$sessiontype"
    else
      cmdGnomeOld=""
    fi
  fi
}

getDefaultGnomeCmd ()
{
  uburel=""
  sessiontype=""

  cmdGnome=""

  #
  # Set gnome, gnome-classic or gnome-falback, if available
  #

  getGnomeCommandNewSuSE

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

    return 0
  fi

  getGnomeCommandSessionDebian

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

    return 0
  fi

  getGnomeCommandSession

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

    return 0
  fi

  #
  # Check if gnome-session is available
  #

  if [ ! -x "${GNOME_SESSION_PATH}"  ];
  then
    return 0
  fi

  if [ -f /usr/share/gnome/gnome-version.xml ]  && [ -f /usr/share/gnome-session/sessions/gnome.session ];
  then
    gnomeVersion=$("${GREPCOMMAND}" "<platform>3</platform>" /usr/share/gnome/gnome-version.xml)

    if [ "x${gnomeVersion}" != "x" ];
    then
      sessiontype="gnome"
    fi
  fi

  if [ -f /usr/share/gnome-about/gnome-version.xml ] && [ -f /usr/share/gnome-session/sessions/gnome.session ];
  then
    gnomeVersion=$("${GREPCOMMAND}" "<platform>3</platform>" /usr/share/gnome-about/gnome-version.xml)

    if [ "x${gnomeVersion}" != "x" ];
    then
      sessiontype="gnome"
    fi
  fi

  unityEnabled="1"

  if [ "$system" = "ubuntu" ];
  then

    getUbuntuVersion

    ubuMajorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | ${CUTCOMMAND} -d '.' -f1)
    ubuMinorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | ${CUTCOMMAND} -d '.' -f2)

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

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

    if [[ ("${ubuMajorRel}" -lt "12") || ("${ubuMajorRel}" -eq "12"  &&  "${ubuMinorRel}" -eq "4") ]];
    then
      unityEnabled="0"
    fi

    if [[ ("${ubuMajorRel}" -gt "11") || ("${ubuMajorRel}" -ge "11"  &&  "${ubuMinorRel}" -ge "10") ]];
    then
      if [ -f /usr/share/gnome-session/sessions/ubuntu.session ] && [ "x${unityEnabled}" == "x1" ];
      then
        sessiontype="ubuntu"
      elif [ -f /usr/share/gnome-session/sessions/ubuntu-2d.session ];
      then
        sessiontype="ubuntu-2d"
      elif [ -f /usr/share/gnome-session/sessions/2d-ubuntu.session ];
      then
        sessiontype="2d-ubuntu"
      elif [ -f /usr/share/gnome/gnome-version.xml ] && [ -f /usr/share/gnome-session/sessions/gnome.session ];
      then
        gnomeVersion=$("${GREPCOMMAND}" "<platform>3</platform>" /usr/share/gnome/gnome-version.xml)

        if [ "x${gnomeVersion}" != "x" ];
        then
          sessiontype="gnome"
        fi

      elif [ -f /usr/share/gnome-about/gnome-version.xml ] && [ -f /usr/share/gnome-session/sessions/gnome.session ];
      then
        gnomeVersion=$("${GREPCOMMAND}" "<platform>3</platform>" /usr/share/gnome-about/gnome-version.xml)

        if [ "x${gnomeVersion}" != "x" ];
        then
          sessiontype="gnome"
        fi

      else
        printMsg "Unable to find proper session type for Unity. Falling back to default" "cmd"
      fi
    fi
  fi

  if [ "x$sessiontype" = "x" ] && [ "x$system" = "xlinuxmint" ];
  then
    cmdGnomeOld=""

    return 0
  fi

  if [ "x${sessiontype}" = "x" ];
  then
    if [ -x /etc/gdm/Xsession ];
    then
      cmdGnome="/etc/gdm/Xsession gnome-session"
    elif [ -x /etc/X11/Xsession ];
    then
      cmdGnome="/etc/X11/Xsession gnome-session"
    elif [ ${DBUS} = "1" ] && [ "x${DBUS_PATH}" != "x" ];
    then
      cmdGnome="${DBUS_PATH} --exit-with-session gnome-session"
    else
      cmdGnome=""
    fi
  else
    if [ -x /etc/gdm/Xsession ];
    then
      cmdGnome="/etc/gdm/Xsession 'gnome-session --session=$sessiontype'"
    elif [ -x /etc/X11/Xsession ];
    then
      cmdGnome="/etc/X11/Xsession 'gnome-session --session=$sessiontype'"
    elif [ ${DBUS} = "1" ] && [ "x${DBUS_PATH}" != "x" ];
    then
      cmdGnome="${DBUS_PATH} --exit-with-session 'gnome-session --session=$sessiontype'"
    else
      cmdGnome=""
    fi
  fi
}

getDefaultKDECmd ()
{
  cmdKDE=""

  #
  # Check if startkde is available
  #

  getKDESessionPath
  if [ ! -x "${KDE_SESSION_PATH}"  ];
  then
    return 0
  fi

  if [ "$system" = "ubuntu" ];
  then

    getDistroVersion

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

    if [ "x$ubuMajorRel" = "x16" ] && [ "x$ubuMinorRel" = "x04" ];
    then
      cmdKDE="${DBUS_PATH} --exit-with-session $KDE_SESSION_PATH"
    fi

    if [ ${ubuMajorRel} -ge 20 ] && [ -x /usr/bin/startplasma-x11 ];
    then
      cmdKDE="env XDG_DATA_DIRS=/usr/local/share:/usr/share:/var/lib/snapd/desktop /usr/bin/dbus-launch --sh-syntax --exit-with-session /usr/bin/startplasma-x11"
    fi

    return 0

  fi

  if [ -x /usr/bin/startplasma-x11 ];
  then
    cmdKDE="env -u WAYLAND_DISPLAY /usr/bin/dbus-launch --sh-syntax --exit-with-session /usr/bin/startplasma-x11"
  elif [ -x /etc/kde/kdm/Xsession ];
  then
    cmdKDE="/etc/kde/kdm/Xsession startkde"
  elif [ -x /etc/kde3/kdm/Xsession ];
  then
    cmdKDE="/etc/kde3/kdm/Xsession startkde"
  elif [ -x /etc/X11/Xsession ];
  then
    cmdKDE="/etc/X11/Xsession startkde"
  elif [ ${DBUS} = "1" ] && [ "x${DBUS_PATH}" != "x" ];
  then
    cmdKDE="${DBUS_PATH} --exit-with-session startkde"
  else
    cmdKDE=""
  fi
}

getDefaultXDMCmd ()
{
  cmdXDM=""

  #
  # Check if gdm, kdm or xdm is available
  #

  if [ -x /etc/X11/gdm/Xsession ];
  then
    cmdXDM="/etc/X11/gdm/Xsession default"
  elif [ -x /etc/X11/kdm/Xsession ];
  then
    cmdXDM="/etc/X11/kdm/Xsession default"
  elif [ -x /etc/X11/xdm/Xsession ];
  then
    cmdXDM="/etc/X11/xdm/Xsession default"
  elif [ -x /etc/X11/xinit/Xsession ];
  then
    cmdXDM="/etc/X11/xinit/Xsession default"

  else
    cmdXDM="/etc/X11/Xsession default"
  fi
}

getDefaultLXDECmd ()
{
  cmdLXDE=""

  if [ -x /usr/bin/lxsession ]
  then
    cmdLXDE="/usr/bin/lxsession -e LXDE"
  fi

  if [ "$system" = "ubuntu" ];
  then

    getUbuntuVersion

    ubuMajorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | \
                     ${CUTCOMMAND} -d '.' -f1)
    ubuMinorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | \
                     ${CUTCOMMAND} -d '.' -f2)

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

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

    if [[ ("${ubuMajorRel}" -eq "13"  &&  "${ubuMinorRel}" -ge "10") ]];
    then
      if [ -x /usr/bin/lxsession ]
      then
        cmdLXDE="/usr/bin/lxsession -s Lubuntu -e LXDE"
      fi
    elif [ "${ubuMajorRel}" -ge 14 ] && [ "x$SSHAGENT_PATH" != "x" ] && \
         [ "x$DBUS_PATH" != "x" ] && [ -x "/usr/bin/im-launch" ] && \
         [ -x "/usr/bin/lxsession" ];
    then
        cmdLXDE="$SSHAGENT_PATH $DBUS_PATH --exit-with-session /usr/bin/im-launch /usr/bin/lxsession -s Lubuntu -e LXDE"
    else
      if [ -x /etc/X11/Xsession ]
      then
        if [ -x /usr/bin/startlubuntu ]
        then
          cmdLXDE="/etc/X11/Xsession startlubuntu"
        fi
      fi
    fi
  fi
}

getDefaultXFCECmd ()
{
  cmdXFCE=""

  if [ -x /usr/bin/startxfce4 ];
  then
    cmdXFCE="/usr/bin/startxfce4"
  elif [ -x /usr/bin/X11/startxfce4 ];
  then
    cmdXFCE="/usr/bin/X11/startxfce4"
  fi
}

getDefaultCinnamonCmd ()
{
  cmdCinnamon=""

  if [ -x /usr/bin/cinnamon-session ];
  then
    cmdCinnamon="/usr/bin/cinnamon-session --session cinnamon"
  fi
}

updateDefaultCommandXsession ()
{
  ret_setDefaultCommandXsession=0

  if [ "$system" = "macosx" ];
  then
    return 0
  fi

  if [ ! -r "${CONFIG_FILE}" ];
  then
    ret_setDefaultCommandXsession=1
    return 0
  fi

  isDbusAvailable

  #setting command for GNOME
  getDefaultGnomeCmd

  getDefaultGnomeCmdOld

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

    getValueFromCfgFile "CommandStartGnome" "${CONFIG_FILE}"

    if [ $ret_getValueFromCfgFile = 2 ];
    then
      gnomeOldCommand="$cfg_val"
    fi

    if [ "x${gnomeOldCommand}" = "x${cmdGnomeOld}" ];
    then
      changeKeyAtConfigFile "${CONFIG_FILE}" "CommandStartGnome" "${cmdGnome}"
    fi
  fi

  getValueFromCfgFile "DefaultDesktopCommand" "${CONFIG_FILE}"

  if [ $ret_getValueFromCfgFile = 2 ];
  then
    desktopOldCommand="$cfg_val"
  fi

  if [ "x${cmdGnome}" != "x" ] && [ "x${cmdGnomeOld}" = "x${desktopOldCommand}" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultDesktopCommand" "${cmdGnome}"
  fi
}

setRdpArg()
{
  if [[ "x$RDP_SESSION_PATH" == *"xfreerdp"* ]];
  then
    RDP_ARGUMENTS=" -f"
  else
    RDP_ARGUMENTS=" -f -r sound:local"
  fi
}

setDefaultCommandXsession ()
{
  ret_setDefaultCommandXsession=0

  if [ "$system" = "macosx" ];
  then
    return 0
  fi

  if [ ! -r "${CONFIG_FILE}" ];
  then
    ret_setDefaultCommandXsession=1
    return 0
  fi

  isDbusAvailable

  #
  # Setting command for GNOME.
  #

  getDefaultGnomeCmd
  if [ "x${cmdGnome}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "CommandStartGnome" "${cmdGnome}"
  fi

  #
  # Setting command for KDE.
  #

  getDefaultKDECmd
  if [ "x${cmdKDE}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "CommandStartKDE" "${cmdKDE}"
  fi

  #
  # Setting command for XDM.
  #

  getDefaultXDMCmd
  if [ "x${cmdXDM}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultXSession" "${cmdXDM}"
  fi

  #
  # Setting command for RDP.
  #

  getRDPSessionPath

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

    setRdpArg

    changeKeyAtConfigFile "${CONFIG_FILE}" "CommandStartRDP" "${RDP_SESSION_PATH} $RDP_ARGUMENTS"

  fi

  #
  # Setting command for RFB.
  #

  getVNCSessionPath
  if [ "x${VNC_SESSION_PATH}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "CommandStartRFB" "${VNC_SESSION_PATH} -fullscreen"
  fi

  #
  # Setting command for LXDE.
  #

  getDefaultLXDECmd

  #
  # Setting command for XFCE.
  #

  getDefaultXFCECmd

  #
  # Setting command for Cinnamon.
  #

  getDefaultCinnamonCmd

  #
  # Setting command for Default.
  #

  if [ "x${cmdGnome}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultDesktopCommand" "${cmdGnome}"
  elif [ "x${cmdKDE}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultDesktopCommand" "${cmdKDE}"
  elif [ "x${cmdLXDE}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultDesktopCommand" "${cmdLXDE}"
  elif [ "x${cmdXFCE}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultDesktopCommand" "${cmdXFCE}"
  elif [ "x${cmdCinnamon}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultDesktopCommand" "${cmdCinnamon}"
  elif [ "x${cmdXDM}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultDesktopCommand" "${cmdXDM}"
  fi
}

SetCupsKey ()
{

  printMsg "Inspecting local CUPS environment" "cmd"

  CUPSaction="${1}"

  CUPS_BACKEND=""
  CUPS_BIN=""
  CUPS_SBIN=""


  for tmp in "${CUPS_PATH[@]}"; do
    if [ "x${CUPS_BACKEND}" = "x" ];
    then
      if [ -d "${tmp}/lib64/cups/backend" ];
      then
        CUPS_BACKEND="${tmp}/lib64/cups/backend";
      elif [ -d "${tmp}/lib/cups/backend" ];
      then
        CUPS_BACKEND="${tmp}/lib/cups/backend";
      elif [ -d "${tmp}/cups/lib/cups/backend" ];
      then
        CUPS_BACKEND="${tmp}/cups/lib/cups/backend";
      elif [ -d "${tmp}/cups/backend" ];
      then
        CUPS_BACKEND="${tmp}/cups/backend"
      fi
    fi

    if [ "x${CUPS_BIN}" = "x" ];
    then
      if [ -x "${tmp}/lpoptions" ];
      then
        CUPS_BIN="${tmp}"
      elif [ -x "${tmp}/bin/lpoptions" ];
      then
        CUPS_BIN="${tmp}/bin"
      fi
    fi

    if [ "x${CUPS_SBIN}" = "x" ];
    then
      if [ -x "${tmp}/cupsd" -a -x "${tmp}/lpadmin" ];
      then
        CUPS_SBIN="${tmp}"
      elif [ -x "${tmp}/sbin/cupsd" -a -x "${tmp}/sbin/lpadmin" ];
      then
        CUPS_SBIN="${tmp}/sbin"
      fi
    fi

    if [ "x${CUPS_BACKEND}" != "x" -a "x${CUPS_BIN}" != "x" -a "x${CUPS_SBIN}" != "x" ];
    then
      break
    fi
  done

  if [ "x${CUPS_BACKEND}" != "x" -a "x${CUPS_BIN}" != "x" -a "x${CUPS_SBIN}" != "x" ];
  then

    if [ "x${CUPSaction}" = "xupdate" ];
    then

      getValueFromCfgFile "EnableCUPSSupport" "${CONFIG_FILE}"

      printUpdateCUPSMessage="0"

      if [ $ret_getValueFromCfgFile = 2 ];
      then
        if [ "x$cfg_val" = "x0" ];
        then
          printUpdateCUPSMessage="1"
        fi
      elif [ $ret_getValueFromCfgFile = 1 ];
      then
        printUpdateCUPSMessage="1"
      else
        printUpdateCUPSMessage="1"
      fi

      if [ "x${printUpdateCUPSMessage}" = "x1" ];
      then
        "${ECHOCOMMAND}" ""
        "${ECHOCOMMAND}" "CUPS support is available. You can enable this by running:"
        "${ECHOCOMMAND}" "${NX_ROOT}/scripts/setup/nxnode --printingsetup"
        "${ECHOCOMMAND}" ""
      fi

    else
      changeKeyAtConfigFile "${CONFIG_FILE}" "EnableCUPSSupport" "1"
      if [ "${ret_changeKeyAtConfigFile}" = "x1" ];
      then
        SHOWCUPSINFO="yes"
      fi

      changeKeyAtConfigFile "${CONFIG_FILE}" "CUPSBackendPath" "${CUPS_BACKEND}"
      if [ "${ret_changeKeyAtConfigFile}" = "x1" ];
      then
        SHOWCUPSINFO="yes"
      fi

      changeKeyAtConfigFile "${CONFIG_FILE}" "CUPSBinPath" "${CUPS_BIN}"
      if [ "${ret_changeKeyAtConfigFile}" = "x1" ];
      then
        SHOWCUPSINFO="yes"
      fi

      changeKeyAtConfigFile "${CONFIG_FILE}" "CUPSSbinPath" "${CUPS_SBIN}"
      if [ "${ret_changeKeyAtConfigFile}" = "x1" ];
      then
        SHOWCUPSINFO="yes"
      fi

    fi

  else
    SHOWCUPSINFO="yes"
  fi

}

checkCupsConfig ()
{
  CUPSaction="$1"

  ret_checkCupsConfig=0

  if [ ! -r "${CONFIG_FILE}" ];
  then
    ret_checkCupsConfig=1
    return 0
  fi

  printMsgUpdateEntriesInConfigFile "CUPS"
  SetCupsKey "${CUPSaction}"
}

nxPrintDriverCache ()
{
  runCommand "'${NODE_ETC_SCRIPT}' --cupsdriversupdate --subprocess 1>/dev/null" "Error while updating printing infrastructure" "cmd"
  if [ $? != 0 ];
  then
    SHOWCUPSINFO="yes"
  fi
}

setSystemLogFileKey ()
{
  if [[ $(${GREPCOMMAND} "Point node to log to a specific file. If this key is commented on" "${CONFIG_FILE}") ]]; then
    ${AWKCOMMAND} '{ gsub("Point node to log to a specific file. If this key is commented on","Point the node to log to a specific file. The default log file is\n# /Library/Application Support/NoMachine/var/log/server.log on Mac",$0); print $0  }' ${CONFIG_FILE} > ${CONFIG_FILE}.tmp
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${AWKCOMMAND} '{ gsub("Linux, node writes logs to system log.","OS X, %PROGRAMDATA%/NoMachine/var/log/server.log on Windows and\n# /usr/NX/var/log/server.log on Linux.",$0); print $0  }' ${CONFIG_FILE} > ${CONFIG_FILE}.tmp
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    if [[ $(${GREPCOMMAND} "#SystemLogFile" "${CONFIG_FILE}") ]]; then
      setValueAtCfgFile "${CONFIG_FILE}" "#SystemLogFile" "${NX_VAR_DIR}/log/server.log"
    fi
  else
    if [[ $(${GREPCOMMAND} "#SystemLogFile" "${CONFIG_FILE}") ]]; then
      setValueAtCfgFile "${CONFIG_FILE}" "#SystemLogFile" "${NX_VAR_DIR}/log/server.log"
    fi
  fi
}

setDefaultConsoleKey ()
{
  DEFAULTCONSOLE=""

  if [ "x$XTERMCOMMAND" != "x" ] && \
     [ $("$WHICHCOMMAND" "$XTERMCOMMAND" 2> /dev/null) ];
  then
    DEFAULTCONSOLE="xterm"
  elif [ "x$GNOMETERMINALCOMMAND" != "x" ] && \
       [ $("$WHICHCOMMAND" "$GNOMETERMINALCOMMAND" 2> /dev/null) ];
  then
    DEFAULTCONSOLE="gnome-terminal"
  elif [ "x$KONSOLECOMMAND" != "x" ] && \
       [ $("$WHICHCOMMAND" "$KONSOLECOMMAND" 2> /dev/null) ];
  then
    DEFAULTCONSOLE="konsole"
  elif [ "x$XFCE4COMMAND" != "x" ] && \
       [ $("$WHICHCOMMAND" "$XFCE4COMMAND" 2> /dev/null) ];
  then
    DEFAULTCONSOLE="xfce4-terminal"
  elif [ "x$LXTERMINALCOMMAND" != "x" ] && \
       [ $("$WHICHCOMMAND" "$LXTERMINALCOMMAND" 2> /dev/null) ];
  then
    DEFAULTCONSOLE="lxterminal"
  elif [ "x$DEEPINTERMINALCOMMAND" != "x" ] && \
       [ $("$WHICHCOMMAND" "$DEEPINTERMINALCOMMAND" 2> /dev/null) ];
  then
    DEFAULTCONSOLE="deepin-terminal"
  fi

  if [[ "x${DEFAULTCONSOLE}" != "x" ]]; then
    changeKeyAtConfigFile "${CONFIG_FILE}" "DefaultConsole" "${DEFAULTCONSOLE}"
  fi
}

setCommandStartRDPKey ()
{
  if [[ $(${GREPCOMMAND} "CommandStartRDP" "${CONFIG_FILE}") ]]; then
    getValueFromCfgFile "CommandStartRDP" "${CONFIG_FILE}"
    if [[ "${cfg_val}" != *"-r sound:local"* ]]; then
      getRDPSessionPath
      if [[ "${cfg_val}" = "${RDP_SESSION_PATH} -f" ]]; then

        setRdpArg

        if [[ "${grep_out}" = *"#CommandStartRDP"* ]]; then
          changeKeyAtConfigFile "${CONFIG_FILE}" "#CommandStartRDP" "${RDP_SESSION_PATH} $RDP_ARGUMENTS"
        else
          changeKeyAtConfigFile "${CONFIG_FILE}" "CommandStartRDP" "${RDP_SESSION_PATH} $RDP_ARGUMENTS"
        fi
      fi
    fi
  fi
}

updateUserScriptKeys ()
{
  command="${GREPCOMMAND} 'UserScriptBeforeSessionStart' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/# the session start-up. The script can accept session ID, username.*/# the session start-up. The script can accept session ID, username,/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# and session type as its input./# session type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptAfterSessionStart' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/# session start-up. The script can accept session ID, username and/# session start-up. The script can accept session ID, username, ses-/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# session type as its input./# sion type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptBeforeSessionDisconnect' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/# the session is disconnected. The script can accept session ID and/# the session is disconnected. The script can accept session ID, user-/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# username as its input./# name, session type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptAfterSessionDisconnect' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/session is disconnected. The script can accept session ID and user-/session is disconnected. The script can accept session ID, username,/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# name as its input./# session type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptBeforeSessionClose' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/# session is closed. The script can accept session ID and username as/# session is closed. The script can accept session ID, username, ses-/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# name as its input./# sion type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptAfterSessionClose' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/# session is closed. The script can accept session ID and username as/# session is closed. The script can accept session ID, username, ses-/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# its input./# sion type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptBeforeSessionReconnect' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/# the session is reconnected. The script can accept session ID and/# the session is reconnected. The script can accept session ID, user-/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# username as its input./# name, session type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptAfterSessionReconnect' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/session is reconnected. The script can accept session ID and user-/session is reconnected. The script can accept session ID, username,/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# name as its input./# session type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi


  command="${GREPCOMMAND} 'UserScriptAfterSessionFailure' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/# session failure. The script can accept session ID, username and/# session failure. The script can accept session ID, username, ses-/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/# session type as its input./# sion type and display as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi
}

setShareKey ()
{
  actionShareKey="$1"

  predefinedPath="$2"

  if [ "x${LOGFILE}" = "x" ];
  then
    LOGFILE="${UPDATELOG}"
    createLogdirectory
    startLog
    PROCESS="$UPDATE"
  fi

  ret_setShareKey=0

  if [ ! -r "${CONFIG_FILE}" ];
  then
    ret_setShareKey=1
    return 0
  fi

  if [ "x${disable_EnableFileSharing}" = "x1" ]
  then
    
    #
    # upgrade from 3.X with set EnableFileSharing=0
    #

    changeKeyAtConfigFile "${CONFIG_FILE}" "EnableSMBFSSupport" "0"

    #
    # Obsolete key.
    # changeKeyAtConfigFile "${CONFIG_FILE}" "EnableMountShareSSHFS" "0"
    #

    return 0
  fi

  HAVE_CIFS=""
  if [ ${system} != "macosx" ];
  then
    for tmp in "${SMB_PATH[@]}"; do
      if test -x "${tmp}/mount.cifs"
      then
        HAVE_CIFS="X"
        break;
      fi
    done
  else
    for tmp in "${SMB_PATH[@]}"; do
      if test -x "${tmp}/mount_smbfs"
      then
        HAVE_CIFS="X"
        break;
      fi
    done
  fi

  if [ "x${HAVE_CIFS}" = "xX" ];
  then
    EnableSMBFSSupport="1"
  else
    EnableSMBFSSupport="0"
    if [ "x${predefinedPath}" = "x1" ];
    then
      printMsg "Cannot find shares in: ${tmp}" "warn"
    fi
  fi

  if [ "x${actionShareKey}" != "xupdate" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "EnableSMBFSSupport" "${EnableSMBFSSupport}"
  else

      getValueFromCfgFile "EnableSMBFSSupport" "${CONFIG_FILE}"

      printUpdateSMBFSMessage="0"

      if [ $ret_getValueFromCfgFile = 2 ];
      then
        if [ "x$cfg_val" = "x0" ];
        then
          printUpdateSMBFSMessage="1"
        fi
      elif [ $ret_getValueFromCfgFile = 1 ];
      then
        printUpdateSMBFSMessage="0"
      else
        printUpdateSMBFSMessage="0"
      fi


    if [ "x${EnableSMBFSSupport}" = "x1" ] && [ "x${printUpdateSMBFSMessage}" = "x1" ];
    then
      "${ECHOCOMMAND}" ""
      "${ECHOCOMMAND}" "SMBFS support is available. You can enable this by running:"
      "${ECHOCOMMAND}" "${NX_ROOT}/scripts/setup/nxnode --sharingsetup"
      "${ECHOCOMMAND}" ""
    fi
  fi
}

fixTempXDir ()
{
  iceDir="/tmp/.ICE-unix"
  commandMkDir "${iceDir}" "warn"
  commandChownChmod "root:${ROOTGNAME}" "1777" "${iceDir}" "warn"

  x11Dir="/tmp/.X11-unix"
  commandMkDir "${x11Dir}" "warn"
  commandChownChmod "root:${ROOTGNAME}" "1777" "${x11Dir}" "warn"
}

selinux_execstack_files=(
/bin/nxnode.bin
/bin/nxagent
/bin/nxd
/bin/nxavc
/bin/nxlocate
)

selinuxOperations()
{
  setSELinuxStatus

  if [ "${SELINUX_ENABLED}" = "1" ];
  then
    commandRestoreCon "/tmp/.X11-unix" "warn"
    setSELinuxExecStack
  fi

  commandRestoreCon "/tmp/.X11-unix" "warn"
}

disableCupsSupport ()
{
  changeKeyAtConfigFile "${CONFIG_FILE}" "EnableCUPSSupport" "0"
  changeKeyAtConfigFile "${CONFIG_FILE}" "CUPSBackendPath" ""
  changeKeyAtConfigFile "${CONFIG_FILE}" "CUPSBinPath" ""
  changeKeyAtConfigFile "${CONFIG_FILE}" "CUPSSbinPath" ""
}

setNXaddprinterPermissions ()
{
  ret_setNXaddprinterPermissions=0

  tmp=$($AWKCOMMAND -F'"' '/^EnableCUPSSupport/ {print $2}' "${CONFIG_FILE}" 2>& 1)
  if [ $? != 0 ];
  then
    printMsg "Cannot parse file: ${CONFIG_FILE}: ${tmp}" "warn"
    ret_setNXaddprinterPermissions=1
    return 0
  elif [ "x${tmp}" != "x" ];
  then
    if [ "${tmp}" = "0" ];
    then
      printMsg "CUPS support is disabled" "cmd"
      ret_setNXaddprinterPermissions=1
      return 0
    fi
  fi

  if [ "x${CUPS_BIN}" = "x" ];
  then
    tmp=$(${AWKCOMMAND} -F'"' '/^CUPSBinPath/ {print $2}' "${CONFIG_FILE}" 2>& 1)
    if [ $? != 0 ];
    then
      printMsg "Cannot parse file: ${CONFIG_FILE}: ${tmp}" "warn"
      ret_setNXaddprinterPermissions=1
      return 0
    elif [ "x${tmp}" != "x" ];
      then
        CUPS_BIN=${tmp}
      else
        printMsg "Cannot update CUPS infrastructure" "warn"
        printMsg "Check key CUPSBinPath in file: ${CONFIG_FILE}" "cmd"
        ret_setNXaddprinterPermissions=1
        SHOWCUPSINFO="yes"
        return 0
    fi
  fi

  if [ -r "/etc/cups/printers.conf" ];
  then
    printersconf="/etc/cups/printers.conf"
  elif [ -r "/opt/sfw/cups/etc/cups/printers.conf" ];
  then
    printersconf="/opt/sfw/cups/etc/cups/printers.conf"
  elif [ -r "/opt/csw/etc/cups/printers.conf" ];
  then
    printersconf="/opt/csw/etc/cups/printers.conf"
  else
    printersconf=""
    printMsg "Cannot find file: printers.conf" "cmd"
  fi

  if [ -r "/etc/cups/cups-files.conf" ];
  then
    cupsfilesconf="/etc/cups/cups-files.conf"
  elif [ -r "/opt/sfw/cups/etc/cups/cups-files.conf" ];
  then
    cupsfilesconf="/opt/sfw/cups/etc/cups/cups-files.conf"
  elif [ -r "/opt/csw/etc/cups/cups-files.conf" ];
  then
    cupsfilesconf="/opt/csw/etc/cups/cups-files.conf"
  else
    printMsg "Cannot find file: cups-files.conf" "cmd"
    cupsfilesconf=""
  fi

  if [ -r "/etc/cups/cupsd.conf" ];
  then
    cupsdconf="/etc/cups/cupsd.conf"
  elif [ -r "/opt/sfw/cups/etc/cups/cupsd.conf" ];
  then
    cupsdconf="/opt/sfw/cups/etc/cups/cupsd.conf"
  elif [ -r "/opt/csw/etc/cups/cupsd.conf" ];
  then
    cupsdconf="/opt/csw/etc/cups/cupsd.conf"
  else
    printMsg "Cannot find file: cupsd.conf" "warn"
    printMsg "Please verify your CUPS configuration" "warn"
    ret_setNXaddprinterPermissions=1
    SHOWCUPSINFO="yes"
    return 0
  fi

  cupsgroup=""

  if [ -r "${cupsdconf}" ];
  then
    sysgroup=$(${GREPCOMMAND} "SystemGroup" $cupsdconf | ${AWKCOMMAND} '{if ($1 == "SystemGroup") {print $0}}' | ${HEADCOMMAND} -1)
    if [ "x$sysgroup" = "x" ];
    then
      sysgroup_comm=$(${GREPCOMMAND} "SystemGroup" ${cupsdconf} | ${AWKCOMMAND} '{if ($1 ~ /^#/) {print $0}}')
      #    printMsg "SystemGroup commented out in file: ${cupsdconf}" "cmd"
    elif [ "x$sysgroup" != "x" ];
    then
      for i in ${sysgroup};
      do
        commentedout=$(${ECHOCOMMAND} $i | ${GREPCOMMAND} '#')
        if [ "x$commentedout" != "x" ];
        then
          break
        fi

        if [ "x$i" != "xroot" ] && [ "x$i" != "xSystemGroup" ];
        then
          cupsgroup="$i"
          printMsg "CUPS SystemGroup: ${cupsgroup}. Base on file: ${cupsdconf}" "cmd"
          break
        elif [ "x$i" = "xroot" ];
        then
          cupsgroup="$i"
        fi
      done

      if [ "x$cupsgroup" = "x" ];
      then
        printMsg "Empty value of SystemGroup key in file: ${cupsdconf}" "cmd"
      fi

    fi
  fi

  if [ "x$cupsgroup" = "x" ] && [ -r "${cupsfilesconf}" ];
  then
    sysgroup=$(${GREPCOMMAND} "SystemGroup" $cupsfilesconf | ${AWKCOMMAND} '{if ($1 == "SystemGroup") {print $0}}' | ${HEADCOMMAND} -1)
    if [ "x$sysgroup" = "x" ];
    then
      sysgroup_comm=$(${GREPCOMMAND} "SystemGroup" ${cupsfilesconf} | ${AWKCOMMAND} '{if ($1 ~ /^#/) {print $0}}')
#     printMsg "SystemGroup commented out in file: ${cupsfilesconf}" "cmd"
    elif [ "x$sysgroup" != "x" ];
    then
      for i in ${sysgroup};
      do
        commentedout=$(${ECHOCOMMAND} $i | ${GREPCOMMAND} '#')
        if [ "x$commentedout" != "x" ];
        then
          break
        fi

        if [ "x$i" != "xroot" ] && [ "x$i" != "xSystemGroup" ];
        then
          cupsgroup="$i"
          printMsg "CUPS SystemGroup: ${cupsgroup}. Base on file: ${cupsfilesconf}" "cmd"
          break
        elif [ "x$i" = "xroot" ];
        then
          cupsgroup="$i"
        fi
      done

      if [ "x$cupsgroup" = "x" ];
      then
        printMsg "Empty value of SystemGroup key in file: ${cupsfilesconf}" "cmd"
      fi
    fi
  fi


  if [ "x$cupsgroup" = "x" ];
  then
    getGroupOwnerCertsDir
    if [ "$ret_getGroupOwnerCertsDir" = "0" ];
    then
      cupsgroup="$groupOwner"
      printMsg "CUPS SystemGroup: ${cupsgroup}. Base on certs directory" "cmd"
    fi
  fi

  if [ "x${cupsgroup}" = "x" ] && [ -r "${printersconf}" ];
  then
    cupsgroup=$(${LSCOMMAND} -l ${printersconf} | ${AWKCOMMAND} -F' '  '{print $4}' 2>& 1)
    if [ "$?" != 0 ];
    then
      printMsg "Cannot stat GID of file: ${printersconf}: ${cupsgroup}" "cmd"
      ret_setNXaddprinterPermissions=1
      SHOWCUPSINFO="yes"
      return 0
    elif [ "x$cupsgroup" = "x" ];
    then
      printMsg "Cannot stat GID of file: printers.conf" "cmd"
      ret_setNXaddprinterPermissions=1
      SHOWCUPSINFO="yes"
      return 0
    fi
    cupsgroup=$(${ECHOCOMMAND} $cupsgroup)
    printMsg "CUPS SystemGroup: ${cupsgroup}. Base on file: printers.conf" "cmd"
  fi

  if [ "x${cupsgroup}" = "x" ];
  then
    printMsg "Cannot stat owner group for CUPS" "warn"
    printMsg "Please verify your CUPS configuration" "warn"
    ret_setNXaddprinterPermissions=1
    SHOWCUPSINFO="yes"
    return 0
  fi
}

fixTempXDir__solaris ()
{
  for files in "${NXINITSH}"
  do
    if [ -f "${files}" ];
    then
      commandChownChmodSuid "root:root" "555" "${files}" "error"
    else
      printMsg "No such file: ${files}" "error"

      exit 1
    fi
  done
}

removeSystemConfig ()
{
  rcFile="/etc/rc.local"

  if [ -f "${rcFile}" ];
  then
    if ${GREPCOMMAND} "#nxsetup .*:" "${rcFile}" > /dev/null
    then
      if ${SEDCOMMAND} -e "/^#nxsetup .*:/,/^#nxsetup end\./d" < "${rcFile}" > "${rcFile}.tmp"
      then
        commandRestoreFile "${rcFile}" "tmp"
      fi
    fi
  fi
}

checkNXConfiguration ()
{
  if [ ! -f "${CONFIG_FILE}" ];
  then
    printMsg "Creating configuration in: ${CONFIG_FILE}" "cmd"
    if [ -f "${CONFIG_FILE}.update" ];
    then
      commandCp "${CONFIG_FILE}.update" "${CONFIG_FILE}" "error"
    else
      if [ "$system" = "ubuntu" ];
      then
        syscfg="debian";
      else
        syscfg=$system;
      fi
      if [ -f "${NX_ROOT}/etc/node-${syscfg}.cfg.sample" ];
      then
        commandCp "${NX_ROOT}/etc/node-${system}.cfg.sample" "${CONFIG_FILE}" "error"
      else
        printMsg "Cannot create configuration file" "error"
        exit 1
      fi
    fi
  fi

  commandChownR "${USER_NX}:${ROOTGNAME}" "${NXHOME}"
  commandChmod "0700" "${NXHOME}"

}

createArchFile ()
{
  NODE_DB_ARCH="${NX_VAR_DIR}/db/node/archinfo"

  echo -ne $(${SYSCTLCOMMAND} -b hw.machine) > "${NODE_DB_ARCH}"
}

getSystemInfo ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    createArchFile
  fi


  NODE_DB_HOST="${NX_VAR_DIR}/db/node/hostinfo"
  if [ ! -f "${NODE_DB_HOST}" ];
  then
    commandTouch "${NODE_DB_HOST}" "warn"
  fi

}

setEtcDirPermissions ()
{
  result=$(${IDCOMMAND} ${USER_NX} 2>&1)
  if [ $? = 0 ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc" "warn"
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys/host" "warn"
    commandChown "${USER_NX}:${NX_GROUP}" "${NX_ROOT}/etc/node.cfg" "warn"
  fi
}

setVarDirPermissions ()
{
  #
  # Setting permissions inside NX/VAR directory.
  #

  if [ ! -d "${NX_VAR_DIR}/tmp" ];
  then
    commandMkDir "${NX_VAR_DIR}/tmp" "warn"
  fi

  #
  # var/tmp
  #

  commandChownChmod "${USER_NX}:${ROOTGNAME}" "1755" "${NX_VAR_DIR}/tmp" "warn"

  #
  # var/tmp/nx
  #

  commandChownRIfExist "${USER_NX}:${USER_NX}" "${NX_VAR_DIR}/tmp/nx" "warn"

  #
  # var/log
  #

  commandChownChmod "${USER_NX}:${ROOTGNAME}" "0777" "${NX_VAR_DIR}/log" "warn"

  #
  # var/log/node
  #

  commandChownChmodIfExist "${USER_NX}:${ROOTGNAME}" "700" "${NX_VAR_DIR}/log/node" "warn"

  #
  # var/db/ports.lock
  #

  commandChownIfExist "${USER_NX}:${USER_NX}" "${NX_VAR_DIR}/db/ports.lock" "warn"
}

updateDirectXSupport ()
{
  if [[ ("$major_version" -lt 5) || \
    ("$major_version" -eq 5 && "$minor_version" -lt 1) || \
    ("$major_version" -eq 5 && "$minor_version" -eq 1 && \
    "$maintenance_version" -lt 56) ]] && \
    [ "x$system" != "xmacosx" ];
  then
    getValueFromCfgFile "EnableDirectXSupport" "$CONFIG_FILE"

    if [ "x$ret_getValueFromCfgFile" = "x1" ] && [ "x$cfg_val" = "x1" ];
    then
      "$SEDCOMMAND" 's\^#EnableDirectXSupport 1$\#EnableDirectXSupport 0\' \
           "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
      commandRestoreFile "$CONFIG_FILE" "tmp"
    fi
  fi
}

removeDisplayMonitorNotifications ()
{
  command="${GREPCOMMAND} 'DisplayMonitorNotifications' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ "$outCommand" ];
  then
    getValueFromCfgFile "DisplayMonitorNotifications" "$CONFIG_FILE"
    if [ "x$ret_getValueFromCfgFile" = "x1" ] && [ "x$cfg_val" = "x1" ];
    then
      removeOptionFromCfgNew "DisplayMonitorNotifications" "Enable *or *disable *displaying *the *Monitor *balloon *messages *issued *to"
    fi
  fi
}

updateConfigFile ()
{
  procedure="$1"

  upadetCommandsPath

  #
  # since NX-4.0.286
  #

  command="${GREPCOMMAND} '\(#\)\?DisplayServerVideoCodec ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ $? != 0 ];
  then
echo "#
# Specify the codec to be used for encoding displays. Accepted values
# are 'h264', 'vp8' and 'mjpeg'.
#
#DisplayServerVideoCodec h264
" >> "${CONFIG_FILE}"
  fi

  command="${GREPCOMMAND} '\(#\)\?DisplayServerVideoFrameRate ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
echo "#
# Specify the video frame rate for encoding displays. Accepted values
# are '30','40','50' and '60'.
#
#DisplayServerVideoFrameRate 30
" >> "${CONFIG_FILE}"
  fi

  command="${GREPCOMMAND} '\(#\)\?DisplayServerUseVideoFrameRate ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
echo "#
# Allow NoMachine to use a specific frame rate to encode displays or
# rely on its ability to choose automatically a frame rate depending
# on network conditions.
#
# 1: Enabled. Nomachine uses only the specified frame rate.
#
# 0: Disabled. NoMachine automatically chooses a frame rate.
#
#DisplayServerUseVideoFrameRate 0
" >> "${CONFIG_FILE}"
  fi

  command="${GREPCOMMAND} '\(#\)\?EnableDebug ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
echo "#
# Enable or disable the debug tool when the node program is launched
#
# 1: Enabled. The debug tool specified in the CommandDebug key will
#    be run to debug the node program. This can slow down the exe-
#    cution of the node.
#
# 0: Disabled. Debug tool is not run.
#
#EnableDebug 0
" >> "${CONFIG_FILE}"
  fi

  command="${GREPCOMMAND} '\(#\)\?AcceptedDebuggerCommands ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
echo "#
# Specify path and commands of the debug tool in a comma-separated
# list, e.g. accepted command for Valgrind is '/usr/bin/valgrind.bin'.
#
#AcceptedDebuggerCommands /usr/bin/valgrind.bin
" >> "${CONFIG_FILE}"
  fi

  command="${GREPCOMMAND} '\(#\)\?CommandDebug ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
echo "#
# Specify absolute path of the command to launch a debug tool.
#
#CommandDebug \"\"
" >> "${CONFIG_FILE}"
  fi

  command="${GREPCOMMAND} '\(#\)\?DebugOptions ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
echo "#
# Append arguments to the command used by the Node to launch the
# debug tool
#
# Multiple parameters can be specified by separating them with a blank
# character. For security reasons, no shell interpretation is made.
#
#DebugOptions \"\"
" >> "${CONFIG_FILE}"
  fi

  insertKeytoConfigFile "EnableWhiteboard" "\n\
#\n\
# Enable or disable the whiteboard and chat tool in the Monitor tool.\n\
#\n\
# 1: Enabled. User can run the whiteboard from the Monitor menu.\n\
#\n\
# 0: Disabled. Item 'Shwo the whiteboard' is not accessible in the\n\
#    monitor menu.\n\
#\n\
#EnableWhiteboard 1" "EnableSessionRecording"

  insertKeytoConfigFile "DisplayMonitorIcon" "\n\
#\n\
# Enable or disable displaying the icon of the Monitor application\n\
# in the system tray.\n\
#\n\
# 1: Enabled. The Monitor icon is visible in the system tray.\n\
#\n\
# 0: Disabled. The Monitor icon is hidden. A notification\n\
#    dialog is issued when users are connecting.\n\
#\n\
#DisplayMonitorIcon 1" "EnableWhiteboard"

  display=":0"
  getValueFromCfgFile "DisplayDefault" "$CONFIG_FILE"
  if [ "${ret_getValueFromCfgFile}" = "2" ];
  then
    display="${cfg_val}"
  fi

  insertKeytoConfigFile "PhysicalDisplays" "\n\
#\n\
# Specify the physical display or range of X server displays which are\n\
# made available to NoMachine connections. It is possible to specify a\n\
# single display by display number, e.g. :0, or by port, e.g. 6000.\n\
# Range of displays can be specified as a dash separated list,\n\
# e.g. :0-:7 or, by port number, 6200-6204. By default all displays\n\
# detected as running will be made available for users.\n\
#\n\
#PhysicalDisplays $display" "DisplayMonitorIcon"

  removeOptionFromCfgNew "DisplayDefault" "Specify *on *which *physical *display *the *server *must *connect."

  command="${GREPCOMMAND} 'AgentLightweightMode' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ $? != 0 ];
  then
    insertKeytoConfigFile "AgentX11VectorGraphics" "\n\
#\n\
# X-Window sessions will only use the X protocol compression. Depend-\n\
# ing on the application, this may require less bandwidth and comput-\n\
# ing resources.\n\
#\n\
# 1: Enabled. Enable X11 vector graphics mode.\n\
#\n\
# 0: Disabled. Disable X11 vector graphics mode.\n\
#\n\
#AgentX11VectorGraphics 1" "1"
  fi

  removeDisplayMonitorNotifications

  insertKeytoConfigFile "EnableSoundAlert" "\n\
#\n\
# Enable or disable playing a sound alert when there is an event.\n\
#\n\
# 1: Enabled.  Play a sound when an event occurs, for example\n\
#              when the user connects to the physical desktop.\n\
#              This is the default.\n\
#\n\
# 0: Disabled. Disable acoustic alert.\n\
#\n\
#EnableSoundAlert 1" "AgentLightweightMode"

  insertKeytoConfigFile "EnableServerStatus" "\n\
#\n\
# Enable or disable access to the server status interface.\n\
#\n\
# 1: Enabled. Users can access the server status interface and the\n\
#    provided functionalities. The system  will request administrative\n\
#    credentials for the host machine to allow users to display any\n\
#    security sensitive information or change the settings. This is\n\
#    the default.\n\
#\n\
# 0: Disabled. The 'Server status' item will not be accessible in\n\
#    the system tray menu.\n\
#\n\
#EnableServerStatus 1" "EnableSoundAlert"

  insertKeytoConfigFile "EnableServerPreferences" "\n\
#\n\
# Enable or disable access to the server preferences.\n\
#\n\
# 1: Enabled. Users can access the server preferences. The system\n\
#    will request administrative credentials for the host machine\n\
#    to allow users to change the settings. This is the default.\n\
#\n\
# 0: Disabled. Users will not have access to the server preferences.\n\
#\n\
#EnableServerPreferences 1" "EnableServerStatus"

  insertKeytoConfigFile "AgentLegacyKeyboard" "\n\
#\n\
# Force legacy X11 keyboard support. Enabling this option the display\n\
# server will build the keyboard map using the X11 keycodes, even when\n\
# evdev Linux input driver is supported. The default is to use evdev\n\
# on node machines where it is available.\n\
#\n\
# 1: Enabled. Always use X11 keycodes even if evdev is supported.\n\
#\n\
# 0: Disabled. Use evdev if supported or fall back to X11 keycodes.\n\
#\n\
#AgentLegacyKeyboard 0" "EnableServerPreferences"

  insertKeytoConfigFile "DesktopCommandLibraryPath" "\n\
#\n\
# Specify path to libraries to be added to the command for starting\n\
# a new virtual desktop.\n\
#\n\
#DesktopCommandLibraryPath \\\"\\\"" "AgentLegacyKeyboard"

  insertKeytoConfigFile "DefaultConsole" "\n\
#\n\
# Specify the default console system startup script. This\n\
# doesn't apply to Windows and Mac OS X platforms.\n\
#\n\
#DefaultConsole \\\"\\\"" "DesktopCommandLibraryPath"

  insertKeytoConfigFile "EnableDisplayServerVideoCodec" "\n\
#\n\
# Allow NoMachine to use a specific codec to encode videos or rely on\n\
# its ability to choose the codec depending on network and hardware\n\
# capabilities:\n\
#\n\
# 1: Enabled. Nomachine always uses the specified codec.\n\
#\n\
# 0: Disabled. NoMachine automatically adapts to network conditions\n\
#    and the available hardware.\n\
#\n\
#EnableDisplayServerVideoCodec 0" "DefaultConsole"

  insertKeytoConfigFile "EnableSyslogSupport" "\n\
#\n\
# Enable or disable logging to the system log file, e.g. syslog\n\
# on UNIX based systems and Events log on Windows platforms.\n\
#\n\
# 1: Enabled. The node will log to the system log file.\n\
#\n\
# 0: Disabled. This is the default value, the node will log to\n\
#    the file specified in the SystemLogFile key.\n\
#\n\
#EnableSyslogSupport 0" "EnableDisplayServerVideoCodec"

  insertKeytoConfigFile "KerberosCredentialsRenewal" "\n\
#\n\
# Set how often the server has to renew the Kerberos tickets and AFS\n\
# tokens to let users keep their Kerberos credentials inside the\n\
# session. The default value, 600 seconds, makes the server renew\n\
# tickets each 10 minutes. Multiples of 30 are accepted, 30 seconds\n\
# is the minimum value. Value must be lower than the maximum lifetime\n\
# set on the system for Kerberos credentials.\n\
#\n\
#KerberosCredentialsRenewal 600" "EnableSyslogSupport"

  insertKeytoConfigFile "EnableHardwareEncoding" "\n\
#\n\
# Enable or disable use of the hardware encoder.\n\
#\n\
# 1: Enabled. Use the hardware encoder if supported by the graphics\n\
#    card.\n\
#\n\
# 0: Disabled. Don't use the hardware encoder.\n\
#\n\
#EnableHardwareEncoding 1" "EnableSyslogSupport"

  insertKeytoConfigFile "ProxyPacketPriority" "\n\
#\n\
# Set the DS (Differentiated Services) 8-bit field, previously known\n\
# as ToS (Type of Service), at the IP network layer. Valid values are\n\
# numbers from 0 to 255 in decimal or hexadecimal format (0x00-0xff).\n\
# The six most significant bits should be set to the DSCP values recom-\n\
# mended by RFC-2597 and RFC-2598 (e.g. use 72 or 0x48 for DSCP Class\n\
# AF21). The two least significative bits should be set to 0. It is\n\
# also possible to use the obsolete ToS flags (e.g. 16 or 0x10 for the\n\
# LOWDELAY behaviour).\n\
#\n\
#ProxyPacketPriority 0x48" "EnableHardwareEncoding"

  grep_outDbus=$(${GREPCOMMAND} "EnableDbusLaunch" "${CONFIG_FILE}" 2>/dev/null)

  insertKeytoConfigFile "EnableDbusLaunch" "\n\
#\n\
# Enable or disable the server to execute single commands through\n\
# D-Bus. This key applies only to Linux platforms.\n\
#\n\
# 1: Enabled. The node will use dbus-launch to run single commands\n\
#    such as gnome-terminal. This is required on those distributions\n\
#    which rely on dbus-launch for standard X session in order to let\n\
#    users run NoMachine custom sessions.\n\
#\n\
# 0: Disabled. Do not use dbus-launch for executing single commands.\n\
#\n\
#EnableDbusLaunch 0" "ProxyPacketPriority"

insertKeytoConfigFile "VirtualDesktopVariables" "\n\
#\n\
# Specify path and name to the script to be executed before starting\n\
# the virtual desktop or custom session in order to set environment\n\
# variables in the NoMachine session. Use the following template:\n\
# /NX/scripts/env/nxvdvariables.sh to create\n\
# your own script and place it in a directory accessible by the user,\n\
# e.g: VirtualDesktopVariables /opt/nxscripts/nxvdvariables.sh.\n\
#\n\
#VirtualDesktopVariables \\\"\\\"" "UserScriptAfterSessionFailure"

  if [ "x$grep_outDbus" = "x" ] || [ "x$procedure" = "xinstall" ];
  then

    getDistroVersion

    majorVersion="$($ECHOCOMMAND $ret_DistroVersion | $CUTCOMMAND -d '.' -f1)"

    if [[ (( "x$system" = "xfedora" ) && ("$majorVersion" -ge 24)) ]] ||\
       [[ (( "x$system" = "xdebian" ) && ("$majorVersion" -ge 9)) ]] ||\
       [[ (( "x$system" = "xubuntu" ) && ("$majorVersion" -ge 16)) ]] ||\
       [[ (( "x$system" = "xredhat" ) && ("$majorVersion" -ge 8)) ]] ||\
       [ "x$system" = "xlinuxmint" ];
    then

      setValueAtCfgFile "$CONFIG_FILE" "EnableDbusLaunch" "1"

    fi
  fi

  insertKeytoConfigFile "EnableAcceptingConnection" "\n\
#\n\
# Show or hide the item in the Monitor tool for enabling or disabling\n\
# accepting connections to this physical desktop.\n\
#\n\
# 1: Enabled. The Accepting connection item is shown in the Monitor\n\
#    menu. The desktop owner can switch screen-sharing on/off.\n\
#\n\
# 0: Disabled. The Accepting connection item is not displayed in the\n\
#    Monitor menu.\n\
#\n\
#EnableAcceptingConnection 1" "EnableDbusLaunch"

insertKeytoConfigFile "EnablePublicPrinter" "\n\
#\n\
# Specify if printers will be visible among all connected users or\n\
# available only for the single user. By default printers are all\n\
# public.\n\
#\n\
# 1: Enabled. User can choose to connect the printer in a public or\n\
#    in a private way. This is the default. If the printer is public,\n\
#    it's accessible to all users running a sessions on this host.\n\
#\n\
# 0: Disabled. Users can connect a printer only in a private way. The\n\
#    printer is accessible to the user who connected it.\n\
#\n\
#EnablePublicPrinter 1" "EnableAcceptingConnection"

  insertKeytoConfigFile "UserScriptAfterRemoteResize" "\n\
#\n\
# Specify absolute path of the custom script to be executed after the\n\
# remote screen is resized. The script can accept session ID, user-\n\
# name, session type, display, width and height as its input.\n\
#\n\
#UserScriptAfterRemoteResize \\\"\\\"" "VirtualDesktopVariables"

  insertKeytoConfigFile "EncoderMode" "\n\
#\n\
# Specify the rate control mode for the encoder. Default is 'auto',\n\
# let NoMachine choose automatically the best option. When 'bitrate'\n\
# is set, the encoder will try to give priority to match the target\n\
# bitrate over quality. When 'quality' is set, the encoder will try\n\
# to give priority to match the target quality over bitrate.\n\
#\n\
#EncoderMode auto" "EnableHardwareEncoding"

  insertKeytoConfigFile "EnableEGLCapture" "\n\
#\n\
# Enable or disable EGL screen capture when connecting to a physical\n\
# display on Linux.\n\
#\n\
# 1: Enabled. Use EGL to grab the physical display. This setting is\n\
#    effective only when the desktop environment is Wayland-based.\n\
#\n\
# 0: Disabled. Do not use EGL for screen capture.\n\
#\n\
#EnableEGLCapture 0" "EncoderMode"

  insertKeytoConfigFile "NXRecordingDirectory" "\n\
#\n\
# Specify the absolute path on the server where session recordings\n\
# will be saved, by default %PROGRAMDATA%/NoMachine/var/recording\n\
# on Windows, /Library/Application Support/NoMachine/var/recording\n\
# on macOS and /usr/NX/var/recording/ on Linux.\n\
#\n\
#NXRecordingDirectory ${NX_VAR_DIR}/recording" "EnablePublicPrinter"

  insertKeytoConfigFile "WaylandModes" "\n\
#\n\
# Specify the screen capture methods to be used for sharing a Wayland\n\
# desktop as a comma-separated list in order of preference. Available\n\
# methods are:\n\
#\n\
# drm:        Copy screen buffers through Direct Rendering Manager.\n\
# compositor: Request screen sharing to the desktop compositor.\n\
# egl:        Use the EGL screen capture method.\n\
#\n\
#WaylandModes \\\"egl,drm,compositor\\\"" "EnableEGLCapture"

  insertKeytoConfigFile "EnablePublicDiskSharing" "\n\
#\n\
# Specify if users can connect their disks publicly or privately or\n\
# only privately.\n\
#\n\
# 1: Enabled. User can choose to connect the disk in a public or\n\
#    in a private way. This is the default. When the disk is public,\n\
#    it's accessible to all users running a sessions on this host.\n\
#    It's mounted in the directory set by DiskSharingPublicBasePath.\n\
#\n\
# 0: Disabled. Users can mount the disk only in a private way. Disks\n\
#    are mounted in the directory set by DiskSharingPrivateBasePath\n\
#    and are accessible only by the user who connected them.\n\
#\n\
#EnablePublicDiskSharing 1" "EnablePublicPrinter"

  insertKeytoConfigFile "EnableEGLCapture" "\n\
#\n\
# Enable or disable EGL screen capture when connecting to a physical\n\
# display on Linux.\n\
#\n\
# 1: Enabled. Use EGL to grab the physical display. This setting is\n\
#    effective only when the desktop environment is Wayland-based.\n\
#\n\
# 0: Disabled. Do not use EGL for screen capture.\n\
#\n\
#EnableEGLCapture 1" "EnablePublicDiskSharing"

  insertKeytoConfigFile "CommonLogDirectory" "\n\
#\n\
# Specify path to the directory where NoMachine programs have to log.\n\
# The log directory must be writable by all users who connect by\n\
# NoMachine. By default, nxserver log file is stored\n\
# in the .nx directory under the home of session owner. When this key\n\
# is set, they are stored to the given path and in a unique log file.\n\
# Session logs are stored in sub-directories reporting the display\n\
# number and session id of the correspondent session.\n\
#\n\
#CommonLogDirectory \"\"" "NXRecordingDirectory"

  insertKeytoConfigFile "GPULoadBalancingAlgorithm" "\n\
#\n\
# Specify the algorithm for selecting the GPU to be used for hardware\n\
# encoding a new session (for NVIDIA GPUs only).\n\
#\n\
# none:        a new session uses the encoder of the GPU specified\n\
#              in the key GPUDedicatedDevice or the first available\n\
#              GPU if the key GPUDedicatedDevice is disabled. This\n\
#              is the default.\n\
#\n\
# round-robin: sessions are distributed among GPUs according to a\n\
#              plain round-robin algorithm in a circular way.\n\
#\n\
# load-based:  the GPU with a lesser workload is chosen for each new\n\
#              session.\n\
#\n\
#GPULoadBalancingAlgorithm none" "CommonLogDirectory"

  insertKeytoConfigFile "GPUDedicatedDevice" "\n\
#\n\
# Specify by UUID the NVIDIA GPU to be used for hardware encoding\n\
# when none algorithm is used in the GPULoadBalancingAlgorithm key.\n\
# NoMachine picks the first available GPU if the given UUID cannot be\n\
# found.\n\
#\n\
#GPUDedicatedDevice GPU-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" "GPULoadBalancingAlgorithm"

  insertKeytoConfigFile "ShowDesktopViewed" "\n\
#\n\
# Enable or disable showing a popup to remind that the desktop is\n\
# currently viewed.\n\
#\n\
# 1: Enabled.  A popup on the screen reminds that the desktop is\n\
#                     currently viewed. This is the default.\n\
#\n\
# 0: Disabled. The popup is not displayed while the desktop is\n\
#                      shared.\n\
#\n\
#ShowDesktopViewed 1" "GPUDedicatedDevice"

  insertKeytoConfigFile "UsersDirectoryPath" "\n\
#\n\
# Specify a different path to the default home to create the .nx\n\
# directory for storing session files and user's logs. This doesn't\n\
# apply to the nx user, the NoMachine reserved user necessary for\n\
# internal operation. If it doesn't exist yet, a sub-directory is\n\
# created for the user who's starting a session, named as username.\n\
# The .nx directory is created under that sub-directory. E.g. if this\n\
# key is set to /tmp/nxdir/, when user nxtest runs the first session,\n\
# the /tmp/nxdir/nxtest/.nx will be created. The directory specifed\n\
# in the UsersDirectoryPath key should be writeable for all users or\n\
# alternatively, the administrator should create a directory with\n\
# proper ownership and permissions, named as username, for each of\n\
# the users who need to start sessions there.\n\
#\n\
#UsersDirectoryPath \\\"\\\"" "ShowDesktopViewed"

  insertKeytoConfigFile "EnableAuditlogs" "\n\
#\n\
# Enable or disable the creation of file transfer logs for auditing\n\
# purposes. Logs contain the word 'Audit' and are logged also to\n\
# server log file.\n\
#\n\
# 1: Enabled. File transfer operations are logged into server log.\n\
#\n\
# 0: Disabled. File transfer operations are not logged in server log.\n\
#    This is the default value.\n\
#\n\
#EnableAuditlogs 0" "UsersDirectoryPath"

  insertKeytoConfigFile "EnableAudio" "\n\
#\n\
# Enable or disable audio streaming and microphone forwarding\n\
# during session.\n\
#\n\
# 1: Enabled. Send sound to user’s computer and allow user’s\n\
#    microphone be forwarded to this machine.\n\
#\n\
# 0: Disabled. Sound won’t be streamed to user’s computer and\n\
#    user’s microphone won’t be forwarded to this machine.\n\
#\n\
EnableAudio 1" "EnableAuditlogs"

  insertKeytoConfigFile "EnableScreenBlanking" "\n\
#\n\
# Blanking the physical screen of the machine when somebody connects.\n\
#\n\
# 1: Enabled. The physical screen of this machine is blanked and the\n\
#    local user cannot interact with the desktop while somebody is\n\
#    connected.\n\
#\n\
# 0: Disabled. The physical desktop of this machine is not blanked\n\
#    when somebody is connected. All operations made from the remote\n\
#    user are visible to the local user and the local user can interact\n\
#    with the desktop. This is the default.\n\
#\n\
#EnableScreenBlanking 0" "ShowDesktopViewed"
  
  insertKeytoConfigFile "EnableScreenBlankingEffect" "\n\
#\n\
# Enable or disable the screen shading effect when there is someone\n\
# connected to the physical display and the screen is blanked.\n\
#\n\
# 1: Enabled. Enable the screen shading effect fading from black\n\
#    to different levels of gray.\n\
#\n\
# 0: Disabled. Disable the screen shading effect.\n\
#\n\
EnableScreenBlankingEffect 1" "EnableScreenBlanking"

  insertKeytoConfigFile "CommandStartPipeWire" "\n\
#\n\
# Specify path and name of the command to start Pipewire server.\n\
#\n\
CommandStartPipeWire \\\"/usr/bin/pipewire -c\\\"" "CommandStartPulseAudio"

  checkPipeWire

  if [ "x$procedure" = "xinstall" ];
  then
    uncommentEnableScreenBlankingEffect
  fi

  #
  # This SED command handle all misstypes.
  #

  ${SEDCOMMAND} -e 's/# Enable or disable syslog. NX Node logs to the Syslog on UNIX/# Enable or disable logging to the system log file, e.g. syslog/' \
                -e 's/# based systems, and using Events log on Windows platform./# on UNIX based systems and Events log on Windows platforms./' \
                -e '/# By default NX Node will write logs to the plain file stored in/d' \
                -e '/# a file defined as a value for SystemLogFile configuration key./d' \
                -e 's/# 1: Enabled$/# 1: Enabled. The node will log to the system log file./' \
                -e 's/# 0: Disabled: this is the default value/# 0: Disabled. This is the default value, the server will log to\
#    the file specified in the SystemLogFile key./' \
                -e 's/Mutiple/Multiple/g' \
                -e 's/favorable/favourable/g' \
                -e 's/ballon/balloon/g' \
                -e 's/phisical/physical/g' \
                "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${AWKCOMMAND} '{ gsub("tickets each 10 minutes. Value for this key must be lower than the","tickets each 10 minutes. Multiples of 30 are accepted, 30 seconds\n# is the minimum value. Value must be lower than the maximum lifetime",$0); print $0  }' "${CONFIG_FILE}" | ${AWKCOMMAND} '{ gsub("maximum lifetime set on the system for Kerberos credentials.","set on the system for Kerberos credentials.",$0); print $0  }' > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  setSystemLogFileKey

  if [ "x$operation" = "xinstall" ];
  then
    setDefaultConsoleKey
  fi

  ${SEDCOMMAND} -e 's/#AgentLightweightMode/#AgentX11VectorGraphics/' \
                -e 's/# 1: Enabled. Enable lightweight mode./# 1: Enabled. Enable X11 vector graphics mode./' \
                -e 's/# 0: Disabled. Disable lightweight mode./# 0: Disabled. Disable X11 vector graphics mode./' \
                "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  setCommandStartRDPKey

  updateDirectXSupport

  command="${GREPCOMMAND} '#DisplayServerVideoFrameRate 25' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  
  if [ $? = 0 ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "#DisplayServerVideoFrameRate" "30"

    ${SEDCOMMAND} -e "s/#  are '25','30','40' and '60'./# are '30','40','50' and '60'./g" "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  grepOut="$($GREPCOMMAND 'session on this node for the first time.' $CONFIG_FILE 2>/dev/null)"

  if [ "x$grepOut" != "x" ];
  then

    "$SEDCOMMAND" -e 's/Specify the message to be shown to the user when the user starts the/Specify the message to be shown to the user when the user starts a/' \
                  -e 's/session on this node for the first time./virtual desktop on this host for the first time./' \
                  -e 's/starts a new session on this node./starts a new virtual desktop on this host./' \
                    "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

    commandRestoreFile "${CONFIG_FILE}" "tmp"

  fi

  #
  # Update of UserNXDirectoryPath.
  #   Key changed to UsersDirectoryPath only if UserNXDirectoryPath is disabled.
  #

  grepOut="$($GREPCOMMAND '#UserNXDirectoryPath' $CONFIG_FILE 2>/dev/null)"

  if [ "x$grepOut" != "x" ];
  then
    removeOptionFromCfgNew "UserNXDirectoryPath" "Specify *a *different *path *to *the *default, *i.e. *user"

    insertKeytoConfigFile "UsersDirectoryPath" "\n\
#\n\
# Specify a different path to the default home to create the .nx\n\
# directory for storing session files and user's logs. This doesn't\n\
# apply to the nx user, the NoMachine reserved user necessary for\n\
# internal operation. If it doesn't exist yet, a sub-directory is\n\
# created for the user who's starting a session, named as username.\n\
# The .nx directory is created under that sub-directory. E.g. if this\n\
# key is set to /tmp/nxdir/, when user nxtest runs the first session,\n\
# the /tmp/nxdir/nxtest/.nx will be created. The directory specifed\n\
# in the UsersDirectoryPath key should be writeable for all users or\n\
# alternatively, the administrator should create a directory with\n\
# proper ownership and permissions, named as username, for each of\n\
# the users who need to start sessions there.\n\
#\n\
#UsersDirectoryPath \"\"" "GPUDedicatedDevice"

  fi

  if [ "$major_version" -lt 8 ];
  then
    "$SEDCOMMAND" "s/nxclient/nxrunner/" "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  removeOptionFromCfgNew "FileTransferWarning" "Issue *a *warning *message *when *the *maximum *size *allowed *for *file"
  removeOptionFromCfgNew "FileTransferWarningSize" "Given *a *warning *size *limit, *the *server *sends *a *notify *message *when"
  removeOptionFromCfgNew "FileTransferAuthorization" "Enable *or *disable *the *server *requesting *authorization *to *the *owner"

  grep_out=$(${GREPCOMMAND} "CommandStartLXDE" "${CONFIG_FILE}" 2>/dev/null)

  if [[ "x${grep_out}" != "x" ]]
  then

    grep_out=$(${GREPCOMMAND} "CommandStartCDE" "${CONFIG_FILE}" 2>/dev/null)

    if [[ "x${grep_out}" != "x" ]]
    then
      ${SEDCOMMAND} -e "s/CommandStartLXDE/CommandStartCDE/g" "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
      commandRestoreFile "${CONFIG_FILE}" "tmp"

      removeOptionFromCfgNew "CommandStartCDE" "Specify *path *and *name *of *the *command *to *start *'LXDE'. *This *doesn't"
    else
      removeOptionFromCfgNew "CommandStartLXDE" "Specify *path *and *name *of *the *command *to *start *'LXDE'. *This *doesn't"
    fi

  else
    removeOptionFromCfgNew "CommandStartCDE" "Specify *path *and *name *of *the *command *to *start *'LXDE'. *This *doesn't"
  fi

  if [ "$system" = "debian" ] || [ "x$system" = "xubuntu" ];
  then

    getDistroVersion

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

    if ( [ "${system}x" = "ubuntux" ] && [ ${ubuMajorRel} -eq 17 ] && [ ${ubuMinorRel} -ge 10 ] ) ||
       ( [ "${system}x" = "ubuntux" ] && [ ${ubuMajorRel} -gt 17 ] ) ||
       ( [ "${system}x" = "xdebian" ] && [ ${ubuMajorRel} -ge 9 ] );
    then
      getValueFromCfgFile "DefaultDesktopCommand" "${CONFIG_FILE}"

      if [ "x${cfg_val}" = "x/etc/X11/Xsession 'gnome-session --session=ubuntu'" ]
      then
        ${SEDCOMMAND} -e 's|/etc/X11/Xsession '\''gnome-session --session=ubuntu'\''|dbus-launch --exit-with-session gnome-session --session=ubuntu|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
        commandRestoreFile "${CONFIG_FILE}" "tmp"
      fi
    fi
  fi

  grep_out=$(${GREPCOMMAND} "SystemLogFile" "${CONFIG_FILE}" 2>/dev/null)

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

    "$AWKCOMMAND" "/# 0: Disabled. This is the default value, the node will log to/\
                  {f=1} !f; /# *the file specified in the SystemLogFile key./ \
    {print \"# 0: Disabled. This is the default value, server and webplayer\";
     print \"#    will log to the home of the session owner or to the path\";
     print \"#    specified in the CommonLogDirectory key, if enabled.\";
                  f=0}" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"

    removeOptionFromCfgNew "SystemLogFile" "Point *the *node *to *log *to *a *specific *file. *The *default *log *file *is"
  fi

  grep_out=$(${GREPCOMMAND} "# Specify the video frame rate for encoding displays. Accepted values" "${CONFIG_FILE}" 2>/dev/null)

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

    "$AWKCOMMAND" "/# Specify the video frame rate for encoding displays. Accepted values/\
                  {f=1} !f; /# are '30','40','50' and '60'./ \
    {print \"# Specify the video frame rate for encoding displays. All values\";
     print \"# starting form '1' are accepted. Suggested values are '30', '40'\";
     print \"# '50' and '60'.\";
                  f=0}" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"

  fi

  #
  # Removing ProxyExtraOptions, DisplayServerExtraOptions, DisplayAgentExtraOptions key values (only when commented).
  #

  grep_out=$(${GREPCOMMAND} "#ProxyExtraOptions " "${CONFIG_FILE}" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    ${SEDCOMMAND} -e 's|#ProxyExtraOptions .*|#ProxyExtraOptions|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  grep_out=$(${GREPCOMMAND} "#DisplayServerExtraOptions " "${CONFIG_FILE}" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    ${SEDCOMMAND} -e 's|#DisplayServerExtraOptions .*|#DisplayServerExtraOptions|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  grep_out=$(${GREPCOMMAND} "#DisplayAgentExtraOptions " "${CONFIG_FILE}" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    ${SEDCOMMAND} -e 's|#DisplayAgentExtraOptions .*|#DisplayAgentExtraOptions|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  grep_out=$(${GREPCOMMAND} "#DisplayServerVideoCodec vp8" "${CONFIG_FILE}" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    ${SEDCOMMAND} -e 's|#DisplayServerVideoCodec vp8|#DisplayServerVideoCodec h264|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  grep_out=$(${GREPCOMMAND} "# values are 'vp8','h264'and 'mjpeg'." "${CONFIG_FILE}" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    ${SEDCOMMAND} -e "s|# values are 'vp8','h264'and 'mjpeg'.|# values are 'h264', 'vp8' and 'mjpeg'.|g" "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi
  
  removeOptionFromCfgNew "AlwaysDisplayMonitorWindow" "Enable *or *disable *displaying *the *Monitor *window, .*Server"

  removeOptionFromCfgNew "" "Enable *or *disable *showing *items *for *browsing *existing *connections."

  removeOptionFromCfgNew "FixedResolution" "Set.*fixed *value.*resolution.*remote *screen *in *case"

  removeOptionFromCfgNew "MinimumResolution" "Set *minimum *resolution *allowed.*remote *screen.*case *of"

  removeOptionFromCfgNew "MaximumResolution" "Set *maximum *resolution *allowed.*remote *screen.*case *of"

  removeOptionFromCfgNew "DisplayMonitorNotifications" "Enable or disable*Monitor balloon messages issued to"

  grep_out=$(${GREPCOMMAND} "#UserNXDirectoryPath " "${CONFIG_FILE}" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    removeOptionFromCfgNew "#UserNXDirectoryPath" "Specify a different path to the default.*i.*e.*user.*s home.*where"
  fi
}

updateSuspendKeysDescription ()
{
  ${SEDCOMMAND} 's/session *is *suspended./session is disconnected./g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  runCommand "${MVCOMMAND} -f '${CONFIG_FILE}.tmp' '${CONFIG_FILE}'" "Cannot move file: ${CONFIG_FILE}.tmp to: ${CONFIG_FILE}" "error"
}

upgradeConfigFile ()
{
  ret_upgradeConfigFile=0

  #
  # Replacing NX node by NX Node.
  #

  ${SEDCOMMAND} -e 's/NX node/NX Node/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"
  ${SEDCOMMAND} -e 's/NX agent/NX Agent/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"
  ${SEDCOMMAND} -e 's/NX runner/NX Runner/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${SEDCOMMAND} -e 's/f\.e\./e.g./g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  #
  # Removing the spaces at the end of lines.
  #

  ${SEDCOMMAND} -e 's/ *$//g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  commandMv "${CONFIG_FILE}" "${CONFIG_FILE}.aux"

  command="${GREPCOMMAND} 'Copyright (c) 2001' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
    ${ECHOCOMMAND} "######################################################################
#                                                                    #
#  Copyright (c) 2001, 2025 NoMachine, http://www.nomachine.com.     #
#                                                                    #
#  All rights reserved.                                              #
#                                                                    #
######################################################################
"  > "${CONFIG_FILE}"
  fi

  command="${GREPCOMMAND} 'Some configuration keys are used to set specific limit' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? != 0 ];
  then
    ${ECHOCOMMAND} "#
# Some configuration keys are used to set specific limits, such as the
# maximum size for the session log. To remove a limitation, set the
# corresponding key to value '0' or 'Unlimited'.
"  >> "${CONFIG_FILE}"
  fi

  if [ -f "${CONFIG_FILE}.aux" ];
  then
    ${CATCOMMAND} "${CONFIG_FILE}.aux" >> "${CONFIG_FILE}"
    commandRm "${CONFIG_FILE}.aux"
  fi

  command="${GREPCOMMAND} 'ConfigFileVersion.*=' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e 's/ *# *Set config file format version.*/# Configuration file format version./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ConfigFileVersion *=.*/ConfigFileVersion 4.0/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

  fi

#SessionLogLevel
  command="${GREPCOMMAND} '[#]*SessionLogLevel *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e '/ *# *Set the log level of NX Node. NX Node logs to the syslog all the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Set the log level of NX Node. NX Node logs to the syslog all the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Set the log level of NX Node. NX Node logs to the syslog all the*/# Set log level. Node logs all events that are <= to the level set and\
# according to the following convention:/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/.*# KERN_ERR.*/# KERN_ERR   3: Error condition./' \
                  -e 's/.*# KERN_INFO.*/# KERN_INFO  6: Informational./' \
                  -e 's/.*# KERN_DEBUG.*/# KERN_DEBUG 7: Debug messages./' \
                  -e 's/# *are logged.*/# are logged./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e '/ *# *Note, anyway, that NX Node uses level 6 in the syslog to log the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Note, anyway, that NX Node uses level 6 in the syslog to log the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Note, anyway, that NX Node uses level 6 in the syslog to log the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Note, anyway, that NX Node uses level 6 in the syslog to log the.*//' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e '/ *# *6: This is the default value. Only the important events/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *6: This is the default value. Only the important events*/# 6: Default value. Only relevant events are logged./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "SessionLogLevel"
  fi

#SessionLogClean
  command="${GREPCOMMAND} '[#]*SessionLogClean *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e '/ *# *Enable or disable the automatic clean-up of NX session directories/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Enable or disable the automatic clean-up of NX session directories*/# Enable or disable the automatic clean-up of session directories at\
# the time sessions are terminated./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "SessionLogClean"
  fi

  command="${GREPCOMMAND} '[#]*NodeName *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e 's/ *# *Specify hostname for the NX Node.*/# Specify hostname for the NoMachine node./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "NodeName"
  fi

#ClientLog
  command="${GREPCOMMAND} '[#]*ClientLog *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e '/ *# *Enable or disable NX Node to log the X client stderr./ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Enable or disable NX Node to log the X client stderr./ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Enable or disable NX Node to log the X client stderr./ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Enable or disable NX Node to log the X client stderr./ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Enable or disable NX Node to log the X client stderr./ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Enable or disable NX Node to log the X client stderr./ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Enable or disable NX Node to log the X client stderr.*/# Enable or disable node to log the X clients standard error.\
#\
# 1: Enabled. Stderr of X clients is redirected to '\'clients\''\
#    file in the session directory.\
#\
# 0: Disabled. Stderr of X clients is redirected to \/dev\/null./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "ClientLog"
  fi

  command="${GREPCOMMAND} '[#]*ClientLogLimit *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Set the maximum size allowed for the log of the X clients/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Set the maximum size allowed for the log of the X clients/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Set the maximum size allowed for the log of the X clients.*/# Set the maximum size, expressed in bytes, allowed for the X clients\
# log. Node terminates the session when this limit is exceeded./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    command="${GREPCOMMAND} '#ClientLogLimit *= ' '${CONFIG_FILE}'"
    outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
    if [ $? = 0 ];
    then
      ${SEDCOMMAND} -e 's/#ClientLogLimit = .*/#ClientLogLimit 0/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
      commandRestoreFile "${CONFIG_FILE}" "tmp"
    else
      upgradeKey "ClientLogLimit"
    fi
  fi

  command="${GREPCOMMAND} '[#]*SessionLogLimit *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Set the maximum size allowed for the session log/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Set the maximum size allowed for the session log/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Set the maximum size allowed for the session log.*/# Set the maximum size, expressed in bytes, allowed for the session\n# log. Node terminates the session when this limit is exceeded./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    command="${GREPCOMMAND} '#SessionLogLimit *= ' '${CONFIG_FILE}'"
    outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

    if [ $? = 0 ];
    then
      ${SEDCOMMAND} -e 's/#SessionLogLimit = .*/#SessionLogLimit 0/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
      commandRestoreFile "${CONFIG_FILE}" "tmp"
    else
      upgradeKey "SessionLogLimit"
    fi
  fi

  command="${GREPCOMMAND} '[#]*ClipboardBufferLimit *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Set the maximum amount of data that can be copied from within the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Set the maximum amount of data that can be copied from within the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Set the maximum amount of data that can be copied from within the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Set the maximum amount of data that can be copied from within the*/# Set the maximum amount of data, in bytes, that can be copied from\
# the session to the client. The default value is 0, i.e. unlimited./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    command="${GREPCOMMAND} '#ClipboardBufferLimit *= ' '${CONFIG_FILE}'"
    outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
    if [ $? = 0 ];
    then
      ${SEDCOMMAND} -e 's/#ClipboardBufferLimit = .*/#ClipboardBufferLimit 0/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
      commandRestoreFile "${CONFIG_FILE}" "tmp"
    else
      command="${GREPCOMMAND} '^ *ClipboardBufferLimit *=.*nlimited' '${CONFIG_FILE}'"
      outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
      if [ $? = 0 ];
      then
        ${SEDCOMMAND} -e 's/^ *ClipboardBufferLimit = .*/ClipboardBufferLimit 0/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
        commandRestoreFile "${CONFIG_FILE}" "tmp"
      else
        upgradeKey "ClipboardBufferLimit"
      fi
    fi
  fi

  command="${GREPCOMMAND} '[#]*CommandClient *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Specify path and name of the client to be run by nxnode, nxcomp/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify path and name of the client to be run by nxnode, nxcomp/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Specify path and name of the client to be run by nxnode, nxcomp.*/# Specify path and name of the client program to be run by the node,\
# for example for issuing dialog boxes and messages, instead of the\
# default nxrunner program./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "CommandClient" "1"
  fi

  command="${GREPCOMMAND} '[#]*CommandLsof *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Specify path and name of the command '\'lsof\'' to list open files.*/# Specify path and name of the command '\'lsof\'' to list open files. This\
# doesn'\''t apply to Windows and Mac OS X platforms./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "CommandLsof" "1"
  fi

  command="${GREPCOMMAND} '[#]*CommandXdpyInfo *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e 's/ *# *Specify path and name of the command '\'xdpyinfo\'' for displaying*/# Specify path and name of the command '\'xdpyinfo\'' for displaying info-/' \
                  -e 's/ *# *information about an X server.*/# rmation about an X server./' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"


    upgradeKey "CommandXdpyInfo" "1"
  fi

  upgradeKey "CommandFuser"
  upgradeKey "CommandClient"
  upgradeKey "CommandLsof"

  upgradeKey "CommandXauth"
  ${SEDCOMMAND} -e 's| *#CommandXauth *xauth|#CommandXauth '"${NX_ROOT}"'/bin/nxauth|' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  upgradeKey "SSHAuthorizedKeys"
  ${SEDCOMMAND} -e 's| *#SSHAuthorizedKeys *authorized_keys2|#SSHAuthorizedKeys \$(HOME)/.ssh/authorized_keys2|' \
                -e 's|Specify *the *location *and *file *name *of *the *SSH *authorized *keys|Specify the location and name of the SSH authorized keys file|' \
    "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  upgradeKey "CommandXmodmap"

  command="${GREPCOMMAND} '[#]*CommandStartCDE *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Specify path and name of the command starting '\'CDE\''.*/# Specify path and name of the command to start '\'CDE\''. This applies to\
# Solaris SPARC platforms only./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "CommandStartCDE" "1"
  fi

  command="${GREPCOMMAND} '[#]*CommandStartRDP *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e 's/ *# *Specify path and name of the command to start the RDP Client.*/# Specify path and name of the command to start the RDP Client. If the\
# Server supports RDP sessions, set this key to "rdesktop -f" to use\
# the rdesktop client./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "CommandStartRDP" "1"
  fi

  command="${GREPCOMMAND} '[#]*CommandStartRFB *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e 's/ *# *Specify path and name of the command to start the RFB Client.*/# Specify path and name of the command to start the RFB Client. If the\
# Server supports VNC sessions, set this key to "vncviewer -fullscreen"\
# to use the vncviewer client./' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"


    upgradeKey "CommandStartRFB" "1"
  fi

  upgradeKey "EnableCommandXkbComp"
  upgradeKey "CommandXkbComp"
  upgradeKey "XkbCompKeymapFile"

  command="${GREPCOMMAND} '[#]*AgentFontServer *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Specify the font server to be used by NX [aA]gent. By default the NX/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify the font server to be used by NX [aA]gent. By default the NX/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Specify the font server to be used by NX [aA]gent. By default the NX.*/# By default the agent only uses the X11 system fonts, uncomment this\
# key to enable use of an X Font Server./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "AgentFontServer"
  fi

  command="${GREPCOMMAND} '[#]*DefaultXSession *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Specify the path of default X window system startup script.*/# Specify the path of default X window system startup script. This\
# doesn'\''t apply to Windows and Mac OS X platforms./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "DefaultXSession"
  fi

  command="${GREPCOMMAND} '[#]*DefaultXDPI *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *should normally not be required, but some desktop applications fail*/# should normally not be required, but some less recent desktop appli-/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *to set an appropriate value and fall back to 75 DPI, which is the*/# cations fail to set an appropriate value and fall back to 75 DPI,/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *value reported by default by the X server.*/# which is the default value reported by the X server./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "DefaultXDPI"
  fi

  command="${GREPCOMMAND} '[#]*AgentLibraryPath *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Specify the path of libraries to be added to the agents environment./ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Specify the path of libraries to be added to the agents environment./# Specify path of libraries to be added to the NoMachine agent environ-\
# ment. Be sure that NoMachine libraries are listed first./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/AgentLibraryPath *=.*NX\(.*\)\"/AgentLibraryPath \1/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  command="${GREPCOMMAND} '[#]*ProxyExtraOptions *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Specify a list of comma-separated options to be added to the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of comma-separated options to be added to the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of comma-separated options to be added to the/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/.*Specify a list of comma-separated options to be added to the/# Specify a list of comma-separated options to be added to NoMachine\
# proxy transport./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "ProxyExtraOptions"
  fi

  command="${GREPCOMMAND} '[#]*AgentExtraOptions *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Append arguments to the command line used to run the NX [aA]gent for/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Append arguments to the command line used to run the NX [aA]gent for*/# Append arguments to the command used by the Node to load the display\
# agent connected to the display server./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e '/ *# * character. Note that, for security reasons, no shell interpretation/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e 's/ *# * character. Note that, for security reasons, no shell interpretation.*/# character. For security reasons, no shell interpretation is made./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "AgentExtraOptions" "1"

    ${SEDCOMMAND} -e 's/ *\([#]\) *AgentExtraOptions /#DisplayAgentExtraOptions /' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

  fi

  upgradeKey "DefaultRDPDomain" "1"

  command="${GREPCOMMAND} '[#]*NodeFirstLoginGreeting *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# * If set, the specified message will be provided to the user if this/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e 's/ *# * If set, the specified message will be provided to the user if this.*/# Specify the message to be shown to the user when the user starts the\
# session on this node for the first time./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/[#]*NodeFirstLoginGreeting *=.*Welcome\(.*\)\"/#NodeFirstLoginGreeting "Welcome to your NoMachine session"/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "NodeFirstLoginGreeting" "1"
  fi

  command="${GREPCOMMAND} '[#]*NodeLoginGreeting *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# * If set, the specified message will be provided to the user every/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e 's/ *# * If set, the specified message will be provided to the user every.*/# Specify the message to be shown to the user every time the user\
# starts a new session on this node./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/[#]*NodeLoginGreeting *=.*Welcome\(.*\)\"/#NodeLoginGreeting "Welcome to your NoMachine session"/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "NodeLoginGreeting" "1"

  fi

  #
  # Update of UserNXDirectoryPath.
  #   Key changed to UsersDirectoryPath.
  #

  command="${GREPCOMMAND} '[#]*UserNXDirectoryPath *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# * Specify a different path from the default, i.e. user/# Specify a different path to the default, i.e. user/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# * create a directory, with proper ownership and permissions, named as.*/# create a directory with proper ownership and permissions, named as/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# * doesn'\''t exist yet, NX Node will try to create a sub-directory for*/# doesn'\''t exist yet, node will try to create a sub-directory for/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "UserNXDirectoryPath" "1"
  fi

  upgradeKey "UserScriptBeforeSessionStart" "1"
  upgradeKey "UserScriptAfterSessionStart" "1"

  command="${GREPCOMMAND} '[#]*UserScriptBeforeSessionSuspend *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# * the session is suspended. The script can accept session ID and.*/# the session is disconnected. The script can accept session ID and/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "UserScriptBeforeSessionSuspend" "1"
    renameKey "UserScriptBeforeSessionSuspend" "UserScriptBeforeSessionDisconnect"
  fi

  command="${GREPCOMMAND} '[#]*UserScriptAfterSessionSuspend *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# * session is suspended. The script can accept session ID and.*/# session is disconnected. The script can accept session ID and user-/' \
                  -e 's/ *# * as its input\./# name as its input./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "UserScriptAfterSessionSuspend" "1"
    renameKey "UserScriptAfterSessionSuspend" "UserScriptAfterSessionDisconnect"
  fi

  upgradeKey "UserScriptBeforeSessionClose" "1"
  upgradeKey "UserScriptAfterSessionClose" "1"
  upgradeKey "UserScriptBeforeSessionReconnect" "1"
  upgradeKey "UserScriptAfterSessionReconnect" "1"
  upgradeKey "UserScriptAfterSessionFailure" "1"

  upgradeKey "DiskSharingList" "1"

  command="${GREPCOMMAND} '[#]*NodeConnectionTimeout *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then

    ${SEDCOMMAND} -e 's/ *# * Set for how long NX Node has to wait for a reply from NX Server.*/# Specify for how long the node has to wait for a reply from NoMachine/' \
                  -e 's/ *# * before considering that the connection with the server has been.*/# server before considering that the connection with the server has/' \
                  -e 's/ *# * lost. The default value, 120, lets NX Node wait for 2 minutes.*/# been lost. Default value, 120 seconds, lets node wait for 2 minutes./' \
                  -e 's/ *# * Set this value to 0 to disable timeout on the node.*/# Set this value to 0 to disable timeout on the node./' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "NodeConnectionTimeout"
  fi

    #descripton for keys: CommandStartGnome, CommandStartKDE
    ${SEDCOMMAND} -e 's/ *# * Specify path and name of the command to start the GNOME session.*/# Specify path and name of the command to start '\'GNOME\''. This doesn'\''t\
# apply to Windows and Mac OS X platforms./' \
                  -e 's/ *# * Specify path and name of the command to start the KDE session.*/# Specify path and name of the command to start '\'KDE\''. This doesn'\''t\
# apply to Windows and Mac OS X platforms./' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

  command="${GREPCOMMAND} '[#]*CUPSBinPath *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# * Specify the path of the directory holding CUPS binaries (f.e. the.*/# Specify the path of the directory holding CUPS binaries (e.g. the/' \
                  -e 's/ *# * '\'lpoptions\'' program).*/# '\'lpoptions\'' program). This key is obsolete and used only for retro\
# compatibility./' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "CUPSBinPath"
  fi

  command="${GREPCOMMAND} '[#]*EnableCUPSSupport *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# * Enable or disable CUPS support:.*/# Enable or disable CUPS support. This doesn'\''t apply to Windows plat-\
# forms. This key is obsolete and used only for retro compatibility./' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "EnableCUPSSupport"
  fi

  command="${GREPCOMMAND} '[#]*CUPSSbinPath *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# * for administrative purposes (e.g. '\'cupsd\'' or '\'lpadmin\'').*/# for administrative purposes (e.g. '\'cupsd\'' or '\'lpadmin\''). This key is\
# obsolete and used only for retro compatibility./' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "CUPSSbinPath"
  fi

  command="${GREPCOMMAND} '[#]*ShareBasePath *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# * Specify the path of base directory where the NX [nN]ode has to mount.*/# Specify path of base directory where the node has to mount shares/' \
                  -e 's| *# * shares exported by the user. The default value is $(HOME)/MyShares.*|# exported by the user. Default value is $(HOME)/MyShares. This key\
# is obsolete and used only for retro compatibility.|' \
                  "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "ShareBasePath"
  fi

  insertKeytoConfigFile "SystemLogFile" "\n\
#\n\
# Point the node to log to a specific file. The default log file is\n\
# /Library/Application Support/NoMachine/var/log/server.log on Mac\n\
# OS X, %PROGRAMDATA%/NoMachine/var/log/server.log on Windows and\n\
# /usr/NX/var/log/server.log on Linux.\n\
#\n\
#SystemLogFile /usr/NX/var/log/server.log" "SessionLogLevel"

  insertKeytoConfigFile "DefaultDesktopCommand" "\n\
#\n\
# Specify path and name of the command to start a new virtual desktop,\n\
# by default the X session set on the system.\n\
#\n\
#DefaultDesktopCommand /etc/X11/Xsession default" "AvailableSessionTypes"

  ${SEDCOMMAND} -e 's|#DefaultDesktopCommand /etc/X11/Xsession default|#DefaultDesktopCommand "/etc/X11/Xsession default"|' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  insertKeytoConfigFile "CUPSBackendPath" "\n\
#\n\
# Specify the path of directory holding the CUPS backend. This key is\n\
# obsolete and used only for retro compatibility.\n\
#\n\
# CUPSBackendPath \"\"" "CUPSSbinPath"

  insertKeytoConfigFile "AudioInterface" "\n\
#\n\
# Specify which audio interface should be used to provide sound in\n\
# sessions. Key values depend on the hosting operating system and can\n\
# be 'pulseaudio', 'alsa' or 'disabled' on Linux, and 'nxaudio' or\n\
# 'disabled' on Windows and Mac OS X.\n\
#\n\
# AudioInterface disabled" "UserScriptAfterSessionFailure"

  insertKeytoConfigFile "CommandStartPulseAudio" "\n\
#\n\
# Specify path and name of the command to start PulseAudio server.\n\
#\n\
# CommandStartPulseAudio \"\"" "AudioInterface"

  insertKeytoConfigFile "EnableSMBFSSupport" "\n\
#\n\
# Allow node to use the CIFS (SMB) file-sharing protocol to attach the\n\
# filesystem to the target directory. This key is obsolete and used\n\
# only for retro compatibility.\n\
#\n\
# 1: Enabled. Node uses smbfs to mount and unmount client shares.\n\
#\n\
# 0: Disabled. Node forbids any attempt to mount shares via smbfs.\n\
#\n\
#EnableSMBFSSupport 1" "CommandStartPulseAudio"

  insertKeytoConfigFile "EnableDiskSharing" "\n\
#\n\
# Enable or disable disk sharing:\n\
#\n\
# client: Filesystem on the client can be connected on server side and\n\
#         accessed from the session.\n\
#\n\
# server: Filesystem on the server can be connected on the end-user's\n\
#         machine and accessed through the whole life of the session.\n\
#\n\
# both:   Client and server filesystem can be connected on remote and\n\
#         locale respectively.\n\
#\n\
# none:   Neither client or server filesystem can be connected.\n\
#\n\
#EnableDiskSharing both" "EnableSMBFSSupport"

  insertKeytoConfigFile "DiskSharingPrivateBasePath" "\n\
#\n\
# Specify path to base directory where the node has to mount disks\n\
# accessible only by the user who connected them. Base directory is\n\
# \$(DESKTOP) by default. \$(HOME) and \$(USER) are also accepted values\n\
# and can be concatenated to specify path to a directory, for example\n\
# \$(HOME)/Shares. Target directory must exist on the system.\n\
#\n\
#DiskSharingPrivateBasePath \$(DESKTOP)" "EnableDiskSharing"

  insertKeytoConfigFile "DiskSharingPublicBasePath" "\n\
#\n\
# Specify path to base directory where the node has to mount user's\n\
# disks which are accessible to users running a session on that server.\n\
# Base directory is \$(PUBLIC) by default. \$(PUBLIC) is /Volumes on Mac\n\
# OS X, /media on Linux, C:\\\Users\\\Public on Windows Vista/7/8 and\n\
# %ALLUSERSPROFILE% on XP. \$(USER) is an accepted value and can be\n\
# concatenated to specify path to a directory, for example /tmp/\$(USER).\n\
# Target directory must exist on the system.\n\
#\n\
#DiskSharingPublicBasePath \$(PUBLIC)" "DiskSharingPrivateBasePath"

  insertKeytoConfigFile "DiskSharingList" "\n\
#\n\
# Specify which disks are available to be connected in the session.\n\
# Default value is 'all'. Alternatively, specify path to the disk or\n\
# directory in a list of comma-separated values. \$(HOME) and \$(USER)\n\
# are accepted values. For example \$(HOME)/Volumes/TimeMachine.\n\
#\n\
#DiskSharingList all" "DiskSharingPrivateBasePath"

  insertKeytoConfigFile "EnablePrinterSharing" "\n\
#\n\
# Enable or disable printer sharing\n\
#\n\
# client: Printers on the client can be connected on server side and\n\
#         made available within the session.\n\
#\n\
# server: Printers on the server can be connected on the end-user's\n\
#         machine.\n\
#\n\
# both:   Client and server printers can be connected on remote and\n\
#         locale respectively.\n\
#\n\
# none:   Neither client or server printers can be connected.\n\
#\n\
#EnablePrinterSharing both" "DiskSharingList"

  insertKeytoConfigFile "EnableUSBSharing" "\n\
#\n\
# Enable or disable usb sharing:\n\
#\n\
# client: USB devices on the client can be forwarded on server side and\n\
#         made available within the session\n\
#\n\
# server: USB devices on the server can be connected on the end-user's\n\
#         machine.\n\
#\n\
# both:   Client and server USB devices can be connected on remote and\n\
#         locale respectively.\n\
#\n\
# none:   Neither client or server USB devices can be connected.\n\
#\n\
#EnableUSBSharing both" "EnablePrinterSharing"

  insertKeytoConfigFile "EnableNetworkSharing" "\n\
#\n\
# Enable or disable network services sharing:\n\
#\n\
# client: Network servers on client side can be added and made available\n\
#         within the session.\n\
#\n\
# server: Network server on the server side can be added and made\n\
#         available on the end-user's machine.\n\
#\n\
# both:   Network servers from client and server side can be connected\n\
#         on remote and locale respectively.\n\
#\n\
# none:   Neither client or server side network servers can be\n\
#         connected.\n\
#\n\
#EnableNetworkSharing both" "EnableUSBSharing"

  insertKeytoConfigFile "EnableSmartcardSharing" "\n\
#\n\
# Enable or disable connecting a smartcard reader:\n\
#\n\
# 1: Enabled. The smartcard reader plugged on client side can be\n\
#             forwarded to server side.\n\
#\n\
# 0: Disabled. The smartcard reader cannot be forwarded.\n\
#\n\
EnableSmartcardSharing 1" "EnableNetworkSharing"

  insertKeytoConfigFile "EnableFileTransfer" "\n\
#\n\
# Enable or disable file transfer:\n\
#\n\
# client: Files can be transferred from client machine to the\n\
#         server.\n\
#\n\
# server: Files can be sent from the server to users.\n\
#\n\
# both:   Client and server files can be transferred on remote and\n\
#         locale respectively.\n\
#\n\
# none:   Neither client or server files can be transferred.\n\
#\n\
#EnableFileTransfer both" "EnableSmartcardSharing"

  insertKeytoConfigFile "CommandDebug" "\n\
#\n\
# Specify absolute path of the command to launch a debug tool.\n\
#\n\
#CommandDebug \"\"" "EnableDebug"

  insertKeytoConfigFile "DisplayServerThreads" "\n\
#\n\
# Specify how many CPU cores the display server will use to encode\n\
# display updates. The default value 'auto' allows NoMachine to use\n\
# a default number of threads based on the available cores.\n\
#\n\
#DisplayServerThreads auto" "EnableSMBFSSupport"

  insertKeytoConfigFile "DisplayEncoderThreads" "\n\
#\n\
# Specify how many CPU cores the encoder will use to encode display\n\
# updates. The default value 'auto' allows NoMachine to use a default\n\
# number of threads based on the available cores.\n\
#\n\
#DisplayEncoderThreads auto" "DisplayServerThreads"

  insertKeytoConfigFile "EnableVirtualGLSupport" "\n\
#\n\
# Enable or disable loading VirtualGL libraries when starting virtual\n\
# desktops on Linux.\n\
#\n\
# 1: Enabled. This make OpenGL applications able to use server side\n\
#             graphics hardware.\n\
#\n\
# 0: Disabled. VirtualGL libraries are not loaded.\n\
#\n\
#EnableVirtualGLSupport 0" "EnableCUPSSupport"

  insertKeytoConfigFile "DisplayServerExtraOptions" "\n\
#\n\
# Append arguments to the command used by the Node to load the display\n\
# server program.\n\
#\n\
# Multiple parameters can be specified by separating them with a blank\n\
# character. For security reasons, no shell interpretation is made.\n\
#\n\
#DisplayServerExtraOptions" "EnableVirtualGLSupport"

  insertKeytoConfigFile "ClientConnectionMethods" "\n\
#\n\
# Specify how clients will have to contact the node, by default by\n\
# the NX service. To allow for multiple methods, specify them in a\n\
# comma-separated list. Supported methods are: NX and SSH.\n\
#\n\
ClientConnectionMethods NX,SSH" "DisplayServerExtraOptions"

  insertKeytoConfigFile "DisplayServerPriority" "\n\
#\n\
# Specify process execution priority for the display server loaded by\n\
# the Node. Accepted values are:\n\
#\n\
# low:      process has niceness 19 on Linux and OS X and idle prio-\n\
#           rity on Windows. This is the least favourable scheduling.\n\
#\n\
# normal:   process has niceness 0 set on Linux and OS X and normal\n\
#           priority class on Windows.\n\
#\n\
# high:     process has niceness -10 set on Linux and OS X and high\n\
#           priority class on Windows.\n\
#\n\
# realtime: process has niceness -20 set on Linux and OS X and real\n\
#           time priority class on Windows. This is the most favourable\n\
#\n\
#DisplayServerPriority realtime" "DisplayServerExtraOptions"

  insertKeytoConfigFile "DisplayAgentPriority" "\n\
#\n\
# Specify process execution priority for the display agent loaded by\n\
# the Node and connected to the display server. Accepted values are:\n\
#\n\
# low:      process has niceness 19 on Linux and OS X and idle prio-\n\
#           rity on Windows. This is the least favourable scheduling.\n\
#\n\
# normal:   process has niceness 0 set on Linux and OS X and normal\n\
#           priority class on Windows.\n\
#\n\
# high:     process has niceness -10 set on Linux and OS X and high\n\
#           priority class on Windows.\n\
#\n\
# realtime: process has niceness -20 set on Linux and OS X and real\n\
#           time priority class on Windows. This is the most favourable\n\
#\n\
#DisplayAgentPriority realtime" "DisplayServerPriority"

  insertKeytoConfigFile "EnableFileTransferSizeLimit" "\n\
#\n\
# Enable or disable the server forbidding a file transfer when the\n\
# file size exceeds the configured limit.\n\
#\n\
# 1: Enabled. The server doesn't allow to transfer a file when\n\
#    its size exceeds the configured limit.\n\
#\n\
# 0: Disabled. File transfer is always allowed, even when the file\n\
#    is largen than the size limit.\n\
#\n\
#EnableFileTransferSizeLimit 0" "FileTransferAuthorization"

  insertKeytoConfigFile "FileTransferSizeLimit" "\n\
#\n\
# Set the maximum size for transferred files, in bytes. The default\n\
# value is 104857600 B, 100MB.\n\
#\n\
#FileTransferSizeLimit 104857600" "EnableFileTransferSizeLimit"

  insertKeytoConfigFile "FileTransferSavePath" "\n\
#\n\
# Specify path of base directory where the node has to save files\n\
# uploaded to the server. Base directory is \$(DESKTOP) by default.\n\
# \$(HOME) and \$(USER) are also accepted values and can be concatenated\n\
# to specify path to a directory, for example \$(HOME)/Shares.\n\
# Target directory must exist on the system.\n\
#\n\
#FileTransferSavePath \$(DESKTOP)" "FileTransferWarningSize"

  insertKeytoConfigFile "FileTransferSaveForcePath" "\n\
#\n\
# Enable or disable saving a transferred file to the specified directory.\n\
#\n\
# 1: Enabled. Given the path to be used, the server always save a\n\
#    transferred file to that directory.\n\
#\n\
# 0: Disabled. User is always asked where to save the transferred\n\
#    file.\n\
#\n\
#FileTransferSaveForcePath 0" "FileTransferSavePath"

  #
  # Removing AgentExtraOptionsRFB and AgentExtraOptionsRDP keys.
  #

  printMsgRemoveKeyFromConfigFile "AgentExtraOptionsRFB"
  printMsgRemoveKeyFromConfigFile "AgentExtraOptionsRDP"

  command="${GREPCOMMAND} '^ *EnableFileSharing *= .*0.*' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

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

  #
  # Removing old keys.
  #

  removeOldOptionsFromCfg
}

removeOldOptionsFromCfg ()
{
  removeOptionFromCfg "EnablePrivilegedSmbScripts" "Allow *the *server *to *use *the *privileged *scripts *to *manage *the *SMB"
  removeOptionFromCfg "EnablePulldownMenu" "Enable *or *disable *the *pulldown *dialog, *which *provides *a *graphical"
  removeOptionFromCfg "DefaultXWM" "Specify *the *default *Window *Manager *to *be *used *when *running *single"
  removeOptionFromCfg "MountShareMode" "Specify *if *NX *Node *has *to *mount *the *shares *by *using *the *real *host"
  removeOptionFromCfg "MountShareProtocol" "Specify *the *file-sharing *protocol *to *be *used *for *attaching *the"
  removeOptionFromCfg "EnableFileSharing" "Allow *the *node *to *use *privileged *scripts *to *manage *the *shares"
  removeOptionFromCfg "EnableUnencryptedSession" "Enable *or *disable *SS. *encryption *of *all *traffic *between *server *and"

  removeOptionFromCfg "ProxyTCPNodelay" "Enable *or *disable *TCP_NODELAY *setting *in *NX *proxy"
  removeOptionFromCfg "CUPSAddPrinterMode" "Specify *if *NX *Node *has *to *add *shared *printers *to *CUPS"
  removeOptionFromCfg "SSHDPort" "Specify *the *TCP *port *where *the *NX *Node *SSHD *daemon *is *running"
  removeOptionFromCfg "SSHDCheckIP" "Accept *or *refuse *the *NX *Client *connection *if *SSHD *does *not *export"
  removeOptionFromCfg "EnableSensor" "Enable *or *disable *running *the *NoMachine *Sensor"
  removeOptionFromCfg "StatisticsHost" "Specify *hostname *or *IP *address *where *the *nxstat *process *is *running"
  removeOptionFromCfg "NodeSensorPort" "Specify *port *where *nxsensor *program *is *listening"
  removeOptionFromCfg "ProxyLibraryPath" "Specify *path *of *libraries *to *be *added *to *proxy *environment"

  command="${GREPCOMMAND} ApplicationLibraryPreload '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of libraries to be preloaded in X applications/d' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    printMsgRemoveKeyFromConfigFile "ApplicationLibraryPreload"
  fi

  command="${GREPCOMMAND} ApplicationLibraryPath '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Specify a list of directories to be added to the library path of X/d' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    printMsgRemoveKeyFromConfigFile "ApplicationLibraryPath"
  fi
}

upadetCommandsPath ()
{
  setToolPathInCfg "fuser" "CommandFuser" "1"
  setToolPathInCfg "lsof" "CommandLsof" "1"
  setToolPathInCfg "xdpyinfo" "CommandXdpyInfo" "1"
  setToolPathInCfg "xmodmap" "CommandXmodmap" "1"
  setToolPathInCfg "xkbcomp" "CommandXkbComp" "1"
}

setMultimedia ()
{
  multimediaAction="${1}"

  SHOWAUDIOINFO="no"

  if [ "$system" = "solaris" ];
  then
    checkOSS "${multimediaAction}"

  elif [ "$system" = "macosx" ];
  then
    setupKext "${multimediaAction}" "nxaudio"
  else
    printMsg "Checking for: PipeWire" "onlylog"

    checkPipeWire

    printMsg "Checking for: PulseAudio" "onlylog"

    checkPulseAudio "${multimediaAction}"

    #
    # alsa is not set into AudioInterface key if pipewire of pulseaudio are detected.
    #

    if [ "x$ret_checkPulseAudio" = "x0" ] && [ "x$ret_checkPipeWire" = "x0" ];
    then
      printMsg "PulseAudio and PipeWire not found, checking for: ALSA" "onlylog"
      checkAlsa "${multimediaAction}"
    fi

    if [ "x$ret_checkPipeWire" = "x1" ] || [ "x$ret_checkPulseAudio" = "x1" ];
    then
      printMsg "Configuring: ALSA" "onlylog"
      checkAlsa "configure"
    fi
 
    if [ "x$ret_checkPipeWire" = "x0" ] && [ "x$ret_checkPulseAudio" = "x0" ];
    then
      SHOWAUDIOINFO="yes"
    fi
  fi

  if [ "x${multimediaAction}" = "xupdate" ];
  then
    if [ "x${ret_checkOSS}" = "x0" ] || [ "x${ret_checkPulseAudio}" = "x1" ] || \
       [ "x${ret_checkAlsa}" = "x0" ] ;
    then

      getValueFromCfgFile "AudioInterface" "${CONFIG_FILE}"

      printUpdateAudioMessage="0"

      if [ $ret_getValueFromCfgFile = 2 ];
      then
        if [ "x$cfg_val" = "xdisabled" ];
        then
          printUpdateAudioMessage="1"
        fi
      elif [ $ret_getValueFromCfgFile = 1 ];
      then
        printUpdateAudioMessage="1"
      else
        printUpdateAudioMessage="1"
      fi

      if [ "x${printUpdateAudioMessage}" = "x1" ];
      then
        "${ECHOCOMMAND}" ""
        "${ECHOCOMMAND}" "Audio interface is available. You can enable this by running:"
        "${ECHOCOMMAND}" "${NX_ROOT}/scripts/setup/nxnode --audiosetup"
        "${ECHOCOMMAND}" ""
      fi
    fi
  fi
}

checkOSS ()
{
  multimediaAction="${1}"

  ret_checkOSS="0"

  if [ -a "/dev/dsp" ];
  then
    printMsg "Checking for: OSS: OK" "onlylog"

    if [ "x${multimediaAction}" != "xupdate" ];
    then
      changeKeyAtConfigFile "${CONFIG_FILE}" "AudioInterface" "oss"
    fi

    ret_checkOSS="0"

  else
    printMsg "Checking for: OSS" "onlylog"
    printMsg "Cannot update OSS infrastructure" "warn"
  fi

  SHOWOSSINFO="yes"
}

checkAlsa ()
{
  #
  # Supported action:
  # - update
  # - configure
  #

  checkAlsaAction="${1}"

  ret_checkAlsa=0

  NX_ALSA_CONFIG_FILE="${NX_AUDIO_DIR}/alsa.conf"

  if [ ! -d "${NX_AUDIO_DIR}" ];
  then
    commandMkDir "${NX_AUDIO_DIR}" "warn"
    if [ ${ret_commandMkDir} != 0 ];
    then
      ret_checkAlsa=1
      return 0
    fi
  fi

  if [ -f "${NX_ALSA_CONFIG_FILE}" ];
  then
    return 0
  fi

  if [ -f "${ALSA_CONFIG_FILE}" ];
  then

    commandCp "${ALSA_CONFIG_FILE}" "${NX_ALSA_CONFIG_FILE}" "warn"

    if [ $ret_commandCp = 0 ];
    then
      ${SEDCOMMAND} -e 's|["]~/.asoundrc["]$|"~/.asoundrc"\n\t\t\t\"NX_SESSION_DIR/.asoundrc\"|g' "${NX_ALSA_CONFIG_FILE}" > "${NX_ALSA_CONFIG_FILE}.tmp"
      command="${GREPCOMMAND} NX_SESSION_DIR '${NX_ALSA_CONFIG_FILE}.tmp'"
      outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

      if [ $? != 0 ];
      then
        printMsg "Error while processing file: ${NX_ALSA_CONFIG_FILE}" "warn"
        commandRm "${NX_ALSA_CONFIG_FILE}.tmp" "error"
      else
        commandRestoreFile "${NX_ALSA_CONFIG_FILE}" "tmp"

        if [ "x${checkAlsaAction}" != "xupdate" ] && [ "x${checkAlsaAction}" != "xconfigure" ];
        then
          changeKeyAtConfigFile "${CONFIG_FILE}" "AudioInterface" "alsa"
        fi
      fi
    fi
  else
    if [ -f "${ALSA_ETC_CONFIG_FILE}" ];
    then

      commandCp "${ALSA_ETC_CONFIG_FILE}" "${NX_ALSA_CONFIG_FILE}" "warn"

      if [ $ret_commandCp = 0 ];
      then
        ${SEDCOMMAND} -e 's|["]~/.asoundrc["]$|"~/.asoundrc"\n\t\t\t\"NX_SESSION_DIR/.asoundrc\"|g' "${NX_ALSA_CONFIG_FILE}" > "${NX_ALSA_CONFIG_FILE}.tmp"
        command="${GREPCOMMAND} NX_SESSION_DIR '${NX_ALSA_CONFIG_FILE}.tmp'"
        outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

        if [ $? != 0 ];
        then
          printMsg "Error while processing file: ${NX_ALSA_CONFIG_FILE}" "warn"
          commandRm "${NX_ALSA_CONFIG_FILE}.tmp" "error"
        else
          commandRestoreFile "${NX_ALSA_CONFIG_FILE}" "tmp"

          if [ "x${checkAlsaAction}" != "xupdate" ] && [ "x${checkAlsaAction}" != "xconfigure" ];
          then
            changeKeyAtConfigFile "${CONFIG_FILE}" "AudioInterface" "alsa"
          fi
        fi
      fi
    else
      printMsg "Cannot find ALSA config file: ${ALSA_CONFIG_FILE}" "onlylog"

      if [ "x${checkAlsaAction}" != "xconfigure" ];
      then
        printMsg "Cannot update ALSA infrastructure" "warn"
      fi
    fi
  fi
}

getPulseAudioPath ()
{
  paConfPath="$1"
  ret_getPulseAudioPath=0
  paPath=""

  if [ "x${paConfPath}" = "x" ];
  then
    paConfPath=${PULSEAUDIO_CONF_DIR}
  fi

  if [ ! -f "${paConfPath}/client.conf" ];
  then
    printMsg "Cannot find file: ${paConfPath}/client.conf" "cmd"
    ret_getPulseAudioPath=1
    return 0
  fi

  paPath=$(${GREPCOMMAND} "daemon-binary" "${paConfPath}/client.conf" | ${SEDCOMMAND} -e s/\;.*// | ${AWKCOMMAND} -F ' ' '{print $3}')

  if [ "x${paPath}" != "x" ] && [ -x "${paPath}" ];
  then
    printMsg "Pulseaudio file found in: ${paPath} (client.conf)" "cmd"
    return 0
  else
    if [ "x${paPath}" != "x" ];
    then
      printMsg "Cannot find file: ${paPath}" "cmd"
    fi
  fi

  whichPath "pulseaudio"
  if [ "x${which_out}" != "x" ];
  then
    if [ -x "${which_out}" ];
    then
      paPath="${which_out}"
      printMsg "Pulseaudio file found in: ${paPath}" "cmd"
      return 0
    fi
  fi

  PULSEAUDIO_DEFAULT_PATH="/usr/bin/pulseaudio"
  if [ -x "${PULSEAUDIO_DEFAULT_PATH}" ];
  then
    paPath="${PULSEAUDIO_DEFAULT_PATH}"
    printMsg "Pulseaudio file found in: ${paPath} (default)" "cmd"
    return 0
  fi

  printMsg "Cannot find pulseaudio: ${PULSEAUDIO_DEFAULT_PATH}" "cmd"
  ret_getPulseAudioPath=1
  return 0
}

remove_module_section_PA ()
{
  module="$1"
  file="$2"
  ret_remove_module_section_PA=0

  ${AWKCOMMAND} -v module="${module}" '
    BEGIN{ prn=1; found=0; }
    {
      if ( prn == 0 ) {
        if (  $0 ~ /endif/ ) { prn=1; }
      } else {
        if ( $0 ~ module) {
          if ( $0 ~ /ifexists/ ) {
            prn=0;
          }else {
            if ( $0 !~ /load-module/ ) {
              print $0;
            }
          }
        } else {
          print $0;
        }
      }
    } ' "${file}" > "${file}.tmp"

  commandRestoreFile "${file}" "tmp"

  return 0
}

customizePulseAudioCfg()
{
  ret_customizePulseAudioCfg=0

  if [ ! -d "${NX_AUDIO_DIR}" ];
  then
    commandMkDir "${NX_AUDIO_DIR}" "warn"
  fi

  if [ ! -d "${NX_AUDIO_DIR}" ];
  then
    ret_customizePulseAudioCfg=1
    return 0
  fi

  commandCp "${PULSEAUDIO_CONF_DIR}/client.conf" "${NX_AUDIO_DIR}/" "warn"
  if [ ${ret_commandCp} != 0 ];
  then
    ret_customizePulseAudioCfg=1
    return 0
  fi

  commandCp "${PULSEAUDIO_CONF_DIR}/daemon.conf" "${NX_AUDIO_DIR}/" "warn"
  if [ ${ret_commandCp} != 0 ];
  then
    ret_customizePulseAudioCfg=1
    return 0
  fi

  commandCp "${PULSEAUDIO_CONF_DIR}/default.pa" "${NX_AUDIO_DIR}/" "warn"
  if [ ${ret_commandCp} != 0 ];
  then
    ret_customizePulseAudioCfg=1
    return 0
  fi

  commandChmod "666" "${NX_AUDIO_DIR}/default.pa"
  if [ ${ret_commandChmod} != 0 ];
  then
    ret_customizePulseAudioCfg=1
    return 0
  fi

  ${AWKCOMMAND} 'BEGIN{aux=1} {
               if ($0 ~ /module-udev-detect/ || $0 ~ /module-detect/)
                 {print "#"$0; if ($0 ~ /^ *.ifexists *module-udev-detect/) {aux=0};}
               else if (aux == 0 && $0 !~ /^#/)  {print "#"$0; if ($0 ~ /^\.endif/) {aux=1}}
               else {print $0}}' "${NX_AUDIO_DIR}/default.pa" > "${NX_AUDIO_DIR}/default.pa.tmp"

  if [ -s "${NX_AUDIO_DIR}/default.pa.tmp" ]
  then
    commandMv "${NX_AUDIO_DIR}/default.pa.tmp" "${NX_AUDIO_DIR}/default.pa"
  else
    commandRm "${NX_AUDIO_DIR}/default.pa.tmp"

    printMsg "Disabling PulseAudio modules failed for: module-udev-detect and module-detect" "cmd"
  fi

  commandChmod "644" "${NX_AUDIO_DIR}/daemon.conf"

  if [ ${ret_commandChmod} != 0 ];
  then
    ret_customizePulseAudioCfg=1
    return 0
  fi

  ${SEDCOMMAND} -e "s/.*use-pid-file.*=.*/use-pid-file = no/g" \
                -e "s/.*high-priority.*=.*/high-priority = no/g" \
                -e "s/.*exit-idle-time.*=.*/exit-idle-time = -1/g" "${NX_AUDIO_DIR}/daemon.conf" > "${NX_AUDIO_DIR}/daemon.conf.tmp"

  if [ $? = 0 ];
  then
    printMsg "Changed values for: use-pid-file, high-priority and exit-idle-time in file: ${NX_AUDIO_DIR}/daemon.conf" "cmd"
    commandRestoreFile "${NX_AUDIO_DIR}/daemon.conf" "tmp"
  else
    commandRmTmpIfExist "${NX_AUDIO_DIR}/daemon.conf.tmp"
    ret_customizePulseAudioCfg=1

    return 0
  fi

  remove_module_section_PA "module-esound-protocol-unix" "${NX_AUDIO_DIR}/default.pa"

  if [ ${ret_remove_module_section_PA} != 0 ];
  then
    ret_customizePulseAudioCfg=1

    return 0
  fi

  remove_module_section_PA "module-native-protocol-unix" "${NX_AUDIO_DIR}/default.pa"

  if [ ${ret_remove_module_section_PA} != 0 ];
  then
    ret_customizePulseAudioCfg=1

    return 0
  fi

  remove_module_section_PA "module-x11-publish" "${NX_AUDIO_DIR}/default.pa"

  if [ ${ret_remove_module_section_PA} != 0 ];
  then
    ret_customizePulseAudioCfg=1

    return 0
  fi

  remove_module_section_PA "module-hal-detect" "${NX_AUDIO_DIR}/default.pa"

  if [ ${ret_remove_module_section_PA} != 0 ];
  then
    ret_customizePulseAudioCfg=1

    return 0
  fi

  ${ECHOCOMMAND} "
.ifexists module-x11-publish.so
.nofail
load-module module-x11-publish
.fail
.endif
"  >> "${NX_AUDIO_DIR}/default.pa"

  return 0
}

nxpreloadSetup()
{
  if [ "x${system}" != "xmacosx" ];
  then
    $SEDCOMMAND "s|NX_SYSTEM=\"/usr/NX\"|NX_SYSTEM=\"$NX_ROOT\"|g" "${NXPRELOAD}" > "${NXPRELOAD}".tmp
    commandRestoreFile "$NXPRELOAD" "tmp"
  fi
}

setAudioInterfaceKey ()
{
  #
  # Default value on AudioInterface is "disabled".
  #  Setting pipewire and/or pulseaudio as AudioInterface.
  #

  config_file="${1}"
  interface="${2}"

  printMsg "Setting ${interface} key" "cmd"

  getValueFromCfgFile "AudioInterface" "${CONFIG_FILE}"

  if [ "x${ret_getValueFromCfgFile}" != "x0" ]
  then
    printMsg "\"${cfg_val}\" value detected in AudioInterface key" "cmd"

    if [ "x${cfg_val}" = "xdisabled" ]
    then
      printMsg "Setting AudioInterface key to \"${interface}\"" "cmd"
      changeKeyAtConfigFile "${config_file}" "AudioInterface" "${interface}"

    elif [ "x${cfg_val}" = "xpulseaudio" ] && [ "x${interface}" != "xpulseaudio" ]
    then
      printMsg "Setting AudioInterface key to \"pulseaudio,${interface}\"" "cmd"
      changeKeyAtConfigFile "${config_file}" "AudioInterface" "pulseaudio,${interface}"

    elif [ "x${cfg_val}" = "xpipewire" ] && [ "x${interface}" != "xpipewire" ]
    then
      printMsg "Setting AudioInterface key to \"pipewire,${interface}\"" "cmd"
      changeKeyAtConfigFile "${config_file}" "AudioInterface" "pipewire,${interface}"

    else
      printMsg "No need to change AudioInterface key" "cmd"
    fi
  fi
}

checkPulseAudio ()
{
  multimediaAction="$1"
  paConfPath="$2"
  paPath=""

  enablePA=1

  getPulseAudioPath ${paConfPath}

  if [ ${ret_getPulseAudioPath} = 0 ] && [ "x${paPath}" != "x" ]
  then
    enablePA=1

    customizePulseAudioCfg

    if [ ${ret_customizePulseAudioCfg} != 0 ];
    then
      printMsg "Customizing PulseAudio config files failed" "warn"
      enablePA=0
    fi
  fi

  if [ "x${paPath}" != "x" ] && [ ${enablePA} = 1 ];
  then
    paPath="${paPath} --high-priority=no"

    printMsg "Updating PulseAudio infrastructure" "cmd"

    printMsgUpdateEntriesInConfigFile "PulseAudio"

    changeKeyAtConfigFile "${CONFIG_FILE}" "CommandStartPulseAudio" "$paPath"

    if [ "x${multimediaAction}" != "xupdate" ];
    then
      setAudioInterfaceKey "${CONFIG_FILE}" "pulseaudio"
    fi

    ret_checkPulseAudio=1
  else
    printMsg "Cannot update PulseAudio infrastructure" "cmd"
    paPath=""

    ret_checkPulseAudio=0
  fi
}

setPipeWireCommand ()
{
  PIPEWIRECOMMAND=""
  
  if [ -x "/usr/bin/pipewire" ];
  then
    PIPEWIRECOMMAND="/usr/bin/pipewire"
  elif [ -x "/bin/pipewire" ];
  then
    PIPEWIRECOMMAND="/bin/pipewire"
  fi

  if [ "x$PIPEWIRECOMMAND" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" CommandStartPipeWire "$PIPEWIRECOMMAND -c"
  fi
}

checkPipeWire ()
{
  ret_checkPipeWire=0
  
  out=$(ps aux | ${GREPCOMMAND} -v "grep" | ${GREPCOMMAND} -o "pipewire")

  if [ -f "/usr/bin/pw-cli" ] && [ "x${out}" != "x" ] && [ -f "/usr/bin/pipewire" ]; 
  then
    ret_checkPipeWire=1
  fi

  if [ "x$ret_checkPipeWire" = "x1" ];
  then
    getValueFromCfgFile "AudioInterface" "$CONFIG_FILE"

    if ([ "x$ret_getValueFromCfgFile" = "x1" ] && [ "x$cfg_val" = "xdisabled" ]) || \
       ([ "x$ret_getValueFromCfgFile" = "x2" ] && [ "x$cfg_val" = "xalsa" ]);
    then
      setAudioInterfaceKey "${CONFIG_FILE}" "pipewire"
    fi
  fi
}

cleanRestrictedDirectory ()
{
  if [ -d "${NX_ROOT}/restricted" ];
  then
    commandRmIfExist "${NXPASSWDSH}" "cmd"
    commandRmIfExist "${NXSETKEY}" "cmd"
    commandRmIfExist "${NXINITSH}" "cmd"
    commandRmIfExist "${NXUSERADDSH}" "cmd"
    commandRmIfExist "${NXUSERDELSH}" "cmd"
    commandRmIfExist "${NXLICENSESH}" "cmd"
    commandRmIfExist "${NXUPDATESH}" "cmd"
    commandRmIfExist "${NXINITSH}" "cmd"
    commandRmIfExist "${NXSHAREDMEMSH}" "cmd"
    commandRmIfExist "${NXAMIXERSH}" "cmd"

    commandRmDir "${NX_ROOT}/restricted" "cmd"
  fi
}

setScriptsLogPermissions ()
{
  commandChownChmodIfExist "root:${ROOTGNAME}" "700" "${NX_ROOT}/scripts/log"
}

setScriptsEnvPermissions ()
{
  if [ -f "${NXFORCELOGOUTSH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "755" "${NXFORCELOGOUTSH}"
  else
    printMsg "No such file: ${NXFORCELOGOUTSH}" "warn"
  fi
}

setRestrictedPermissions ()
{
  if [ -f "${NXLICENSESH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXLICENSESH}"
  else
    printMsg "No such file: ${NXLICENSESH}" "warn"
  fi

  if [ -f "${NXUPDATESH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXUPDATESH}"
  else
    printMsg "No such file: ${NXUPDATESH}" "warn"
  fi

  if [ -f "${NXGETCOOKIESH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXGETCOOKIESH}"
  else
    printMsg "No such file: ${NXGETCOOKIESH}" "warn"
  fi

  if [ -f "${NXGETENVIRONMENT}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXGETENVIRONMENT}"
  else
    printMsg "No such file: ${NXGETENVIRONMENT}" "warn"
  fi

  if [ -f "${NXPORTANDCOOKIEGET}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXPORTANDCOOKIEGET}"
  else
    printMsg "No such file: ${NXPORTANDCOOKIEGET}" "warn"
  fi

  #
  # Only in nomachine-cloud-server packages
  # with DEVELOPMENT flag on so WARNINGS are disabled.
  #

  if [ -f "${NXPORTFORWARDADD}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXPORTFORWARDADD}"
  fi

  if [ -f "${NXPORTFORWARDDEL}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXPORTFORWARDDEL}"
  fi

  if [ -f "${NXKILL}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXKILL}"
  else
    printMsg "No such file: ${NXKILL}" "warn"
  fi

  if [ -f "${NXSETKEY}" ]
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXSETKEY}"
  else
    printMsg "No such file: ${NXSETKEY}" "warn"
  fi

  if [ -f "${NXINITSH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXINITSH}"
  else
    printMsg "No such file: ${NXINITSH}" "warn"
  fi

  if [ -f "${NXDISABLEAVCSH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXDISABLEAVCSH}"
  else
    printMsg "No such file: ${NXDISABLEAVCSH}" "warn"
  fi

  if [ -f "${NXUSERADDSH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXUSERADDSH}"
  else
    printMsg "No such file: ${NXUSERADDSH}" "warn"
  fi

  if [ -f "${NXUSERDELSH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXUSERDELSH}"
  else
    printMsg "No such file: ${NXUSERDELSH}" "warn"
  fi

  if [ -f "${NXCOPYSH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXCOPYSH}"
  else
    printMsg "No such file: ${NXCOPYSH}" "warn"
  fi

  if [ -f "${NXTRUNCATESH}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXTRUNCATESH}"
  else
    printMsg "No such file: ${NXTRUNCATESH}" "warn"
  fi

  if [ "x${system}" = "xmacosx" ];
  then
    if [ -f "${NXSHAREDMEMSH}" ];
    then
      commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXSHAREDMEMSH}"
    else
      printMsg "No such file: ${NXSHAREDMEMSH}" "warn"
    fi
    if [ -f "$NXADAPTERSSH" ];
    then
      commandChownChmodSuid "root:${ROOTGNAME}" "744" "$NXADAPTERSSH"
    else
      printMsg "No such file: $NXADAPTERSSH" "warn"
    fi
  fi

  if [ "x${system}" != "xmacosx" ];
  then
    if [ -f "${NXAMIXERSH}" ];
    then
      commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXAMIXERSH}"
    else
      printMsg "No such file: ${NXAMIXERSH}" "warn"
    fi
  fi

  if [ "x${system}" != "xmacosx" ];
  then
    if [ -f "${NXLOGINCTL}" ];
    then
      commandChownChmodSuid "root:${ROOTGNAME}" "744" "${NXLOGINCTL}"
    else
      printMsg "No such file: ${NXLOGINCTL}" "warn"
    fi
  fi

  setNXaddprinterPermissions
}

createLogFiles ()
{
  if [ ! -f "${NX_VAR_DIR}/log/daemon.log" ];
  then
    commandTouch "${NX_VAR_DIR}/log/daemon.log" "warn"
  fi

  commandChownChmod "${USER_NX}:${ROOTGNAME}" "0644" "${NX_VAR_DIR}/log/daemon.log"
}

cleanShareDirectory ()
{
  nxfiles="knotifyrc.artsd knotifyrc.esd mcoprc nxagent.xpm"
  nxdirs="doc fonts.ttf nxkbd"
  for tmpfile in $nxfiles ; do
    if [ -f "${NX_ROOT}/share/$tmpfile" ];
    then
      command="$RMCOMMAND -f '${NX_ROOT}/share/$tmpfile'"
      printMsg "Command: ${command}" "cmd"
      outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
      if [ "$?" != 0 ];
      then
        printMsg "${outCommand}" "cmd"
      else
        printMsg "${outCommand}" "cmd"
        printMsg "Result: OK" "cmd"
      fi
    fi
  done
  for tmpdir in ${nxdirs} ; do
    if [ -d "${NX_ROOT}/share/$tmpdir" ];
    then
      command="${RMCOMMAND} -rf '${NX_ROOT}/share/$tmpdir'"
      printMsg "Command: ${command}" "cmd"
      outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
      if [ "$?" != 0 ];
      then
        printMsg "${outCommand}" "cmd"
      else
        printMsg "${outCommand}" "cmd"
        printMsg "Result: OK" "cmd"
      fi
    fi
  done
}

isFreePackage ()
{
  ret_isFreePackage=1

  getLicenseAcronym

  #version 3.X
  if [ ${ret_getLicenseAcronym:1} = SN ];
  then
    return 0
  fi

  ret_isFreePackage=0
}

fixCUDA()
{
  if [ -f "$NX_ROOT/bin/nxcuinit" ];
  then
    runCommand "$NX_ROOT/bin/nxcuinit" "Error in CUDA initialization." "error"
  fi
}

installPersonal ()
{
  initializeOperation "install"

  printOperationInfo  "install"

  makeNXConfig
  setMultimedia

  setDefaultCommandXsession
  setAvailableSessionTypes

  if [ "${system}" = "macosx" ];
  then
    commandChmod "755" "${NX_ROOT}" "error"
  fi

  if [ -f "${LICENSE_FILE}.sample" ];
  then
    commandRmIfExist "${LICENSE_FILE}" "error"
    commandMv "${LICENSE_FILE}.sample" "${LICENSE_FILE}" "error"
    if [ "${system}" = "macosx" ];
    then
      commandChmod "0444" "${LICENSE_FILE}" "error"
      addNXUserMac
    else
      commandChmod "0400" "${LICENSE_FILE}" "error"
    fi
  fi

  changeKeyAtConfigFile "${CONFIG_FILE}" "SystemLogFile" "${NX_VAR_DIR}/log/server.log"

  if [ ! -d "${NX_VAR_DIR}/tmp" ];
  then
    commandMkDir "${NX_VAR_DIR}/tmp" "warn"
    if [ "${system}" = "macosx" ];
    then
      commandChmod "1755" "${NX_VAR_DIR}/tmp" "warn"
    fi
  fi

  printSummaryInfo "install"

  exit 0
}

updatePersonal ()
{
  if [ "${system}" = "macosx" ];
  then
    if [ ! -f "${CONFIG_FILE}" ];
    then
      installPersonal
      return
    fi
  fi

  initializeOperation "update"
  printOperationInfo  "update"

  makeConfBackup

  makeNXConfig
  setMultimedia  "update"
  setDefaultCommandXsession
  setAvailableSessionTypes

  if [ -f "${LICENSE_FILE}.sample" ];
  then
    commandRmIfExist "${LICENSE_FILE}" "error"
    commandMv "${LICENSE_FILE}.sample" "${LICENSE_FILE}" "error"
    if [ "${system}" = "macosx" ];
    then
      commandChmod "0444" "${LICENSE_FILE}" "error"
    else
      commandChmod "0400" "${LICENSE_FILE}" "error"
    fi
  fi

  if [ ! -d "${NX_VAR_DIR}/tmp" ];
  then
    commandMkDir "${NX_VAR_DIR}/tmp" "warn"
    if [ "${system}" = "macosx" ];
    then
      commandChmod "1755" "${NX_VAR_DIR}/tmp" "warn"
    fi
  fi

  printSummaryInfo "update"

  exit 0
}

setConnectionMethods ()
{
  getLicenseAcronym

  if [ "x${LICENSE_ACRONYM}" = "x" ];
  then
    printMsg "Cannot read license acronym" "warn"
    return 0
  fi

  if [ ${LICENSE_ACRONYM:1} = SE ];
  then
    ret_isSupportedHtd=0
    return 0
  fi

  getValueFromCfgFile "ClientConnectionMethods" "${CONFIG_FILE}"

  if [ ${ret_getValueFromCfgFile} = 1 ];
  then
    setValueAtCfgFile "${CONFIG_FILE}" "ClientConnectionMethods" "NX,SSH"
  fi
}

isServerIncluded ()
{
  ret_isServerIncluded=0

  if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
  then
    if [ -f "${NX_ETC_SERVER}" ];
    then
      ret_isServerIncluded=1
    fi
  fi
}

setUpdateCfg ()
{
  commandChownChmod "nx:${ROOTGNAME}" "644" "${NX_ROOT}/etc/update.cfg" "warn"
}

setAnywhereCfg ()
{
  if [ "${system}" != "macosx" ] && [ -f "${NX_ROOT}/etc/anywhere.cfg" ]; then
    commandChownChmod "nx:${ROOTGNAME}" "644" "${NX_ROOT}/etc/anywhere.cfg" "warn"
  fi
  if [ "${system}" != "macosx" ] && [ -f "${NX_ROOT}/etc/network.cfg" ]; then
    commandChownChmod "nx:${ROOTGNAME}" "644" "${NX_ROOT}/etc/network.cfg" "warn"
  fi
}

setEtcLink ()
{
  ETC_NXNODE="/etc/NX/nxnode"

  if [ ! -h "$ETC_NXNODE" ];
  then
    commandRm "$ETC_NXNODE" "warn"
  fi

  if [ $(${READLINKCOMMAND} "${ETC_NXNODE}" | ${GREPCOMMAND} "nxnode.app") ]
  then
    commandRm "$ETC_NXNODE" "warn"
  fi

  if [ ! -f "$ETC_NXNODE" ];
  then
    commandLn "${NX_ROOT}/../MacOS/nxnode" "$ETC_NXNODE" "error"
  fi
}

procedureInstallBasic ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    getPackagePath "${PACKAGE_NAME}"
    if [ ${ret_getPackagePath} = 0 ];
    then
      if [ "x${ret_packagePath}" = "x${NX_ROOT}" ];
      then
        restoreContextForInstalationDir

        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxnode" --install ${SYSTEM}
        return 0
      else
        getProductName "${PACKAGE_NAME}"
        printMsg "${ret_getProductName} package is already installed in: ${ret_packagePath}"

        return 0
      fi
    else
      restoreContextForInstalationDir

      if [ ! -f "${NX_ROOT}/etc/node.cfg" ];
      then
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxnode" --install --basic
      fi

      return 0
    fi
  fi

  USER_NX="root"

  initializeOperation "install-basic"
  printOperationInfo  "install-basic"

  makeNXConfig
  setConnectionMethods

  printSummaryInfo "install-basic"
  exit 0

}

installPolkitFiles ()
{
  if [ "${system}" != "macosx" ];
  then
    if [ -d "/usr/share/polkit-1/actions/" ];
    then
      system_proxy_policy="org.freedesktop.packagekit.system-network-proxy-configure"

      if [ ! -f "/usr/share/polkit-1/actions/${system_proxy_policy}.policy" ]
      then
        "${CPCOMMAND}" "${NX_ROOT}/share/policy/${system_proxy_policy}.policy" "/usr/share/polkit-1/actions/"
        "${CHMODCOMMAND}" 644 "/usr/share/polkit-1/actions/${system_proxy_policy}.policy"
      fi

      #
      # Restoring default org.freedesktop.packagekit.policy file
      # due to error made in version 5.1.28 (official released in 5.1.40 and 5.1.44).
      #

      lines_nr=0
      getPreviousVersion

      if [ ${major_version} -eq 5 ] && [ ${minor_version} -eq 1 ] && [ ${maintenance_version} -gt 28 ] && [ ${maintenance_version} -le 44 ]
      then
        if [ -f "/usr/share/polkit-1/actions/org.freedesktop.packagekit.policy" ]
        then
          lines_nr=$(${WCCOMMAND} -l < /usr/share/polkit-1/actions/org.freedesktop.packagekit.policy)

          polkit_output=$("${GREPCOMMAND}" "<action id=\"org.freedesktop.packagekit\">" /usr/share/polkit-1/actions/org.freedesktop.packagekit.policy 2>/dev/null)
          polkit_output_lines=$("${GREPCOMMAND}" "yes" /usr/share/polkit-1/actions/org.freedesktop.packagekit.policy 2>/dev/null | "${WCCOMMAND}" -l)
        fi
      fi

      if [ ! -f "/usr/share/polkit-1/actions/org.freedesktop.packagekit.policy" ] ||\
         ( [ $lines_nr -eq 13 ] && [ "${polkit_output}x" != "x" ] && [ $polkit_output_lines -eq 3 ] )
      then
        "${CPCOMMAND}" "${NX_ROOT}/share/policy/org.freedesktop.packagekit.policy" "/usr/share/polkit-1/actions/"
        "${CHMODCOMMAND}" 644 "/usr/share/polkit-1/actions/org.freedesktop.packagekit.policy"
      fi

      #
      # Removing old .policy files (related to colord) due to changed way of granting proper polkit rules
      # (changed in 6.2.3).
      #

      color_create_device_policy="org.freedesktop.color-manager.create-device.policy"
      color_create_device_policy_md5sum="2eb2c22cb870e5b4c1ac39748457e4e5"

      color_policy="org.freedesktop.color"
      color_policy_md5sum="3f7ad0dc895e7cd809da9a3ad7724399"

      #
      # org.freedesktop.color-manager.create-device.policy
      #

      if [ -f "/usr/share/polkit-1/actions/color_create_device_policy" ]
      then
        file_to_remove_md5sum=($("${MD5SUMCOMMAND}" "/usr/share/polkit-1/actions/${color_create_device_policy}"))

        if [ "${file_to_remove_md5sum}x" = "${color_create_device_policy_md5sum}x" ]
        then
          commandRm "/usr/share/polkit-1/actions/${color_create_device_policy}"
        fi
      fi

      #
      # org.freedesktop.color.policy
      #

      if [ -f "/usr/share/polkit-1/actions/${color_policy}" ]
      then
        file_to_remove_md5sum=($("${MD5SUMCOMMAND}" "/usr/share/polkit-1/actions/${color_policy}"))

        if [ "${file_to_remove_md5sum}x" = "${color_policy_md5sum}x" ]
        then
          commandRm "/usr/share/polkit-1/actions/${color_policy}"
        fi
      fi
    fi

    #
    # Installing polkit rule (.pkla) files.
    #

    if [ -d /etc/polkit-1/localauthority/ ]
    then

      if [ ! -d /etc/polkit-1/localauthority/55-org.nomachine.d/ ]
      then
        "${MKDIRCOMMAND}" "/etc/polkit-1/localauthority/55-org.nomachine.d/"
      fi

      getDistroVersion

      ubuntu_major="0"
      ubuntu_minor="0"

      fedora_major="0"

      redhat_major="0"
      redhat_minor="0"

      debian_major="0"

      if [ "${system}x" = "ubuntux" ];
      then
        ubuntu_major=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f1)
        ubuntu_minor=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f2)
      elif [ "${system}x" = "fedorax" ]
      then
        fedora_major=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f1)
      elif [ "${system}x" = "debianx" ]
      then
        debian_major=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f1)
      elif [ "${system}x" = "redhatx" ]
      then
        redhat_major=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f1)
	redhat_minor=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f2)
      fi

      #
      # Ubuntu since 17.10
      # Fedora since 26
      # Debian since 10
      # Redhat/Centos since 7.5
      #

      if ([ ${ubuntu_major} -eq 17 ] && [ ${ubuntu_minor} -eq 10 ]) || [ ${ubuntu_major} -ge 18 ] ||\
         ([ ${redhat_major} -eq 7  ] && [ ${redhat_minor} -ge 5  ]) || [ ${redhat_major} -ge 8  ] ||\
          [ ${fedora_major} -ge 26 ] ||\
	  [ ${debian_major} -ge 10 ]
      then
        "${CPCOMMAND}" "${NX_ROOT}/share/policy/10-org.nomachine.allow.colord.pkla" "/etc/polkit-1/localauthority/55-org.nomachine.d/"
      fi

      #
      # Since fedora 21.
      #

      if [ ${fedora_major} -ge 21 ];
      then
        "${CPCOMMAND}" "${NX_ROOT}/share/policy/10-org.nomachine.allow.pcsc-lite.pkla" "/etc/polkit-1/localauthority/55-org.nomachine.d/"
      fi

      #
      # Since fedora 30, debian 10 and ubuntu 19.10.
      #

      if ([ ${ubuntu_major} -eq 19 ] && [ ${ubuntu_minor} -eq 10 ]) || [ ${ubuntu_major} -gt 19 ] ||\
          [ ${fedora_major} -ge 30 ] ||\
          [ ${debian_major} -ge 10 ]
      then
        "${CPCOMMAND}" "${NX_ROOT}/share/policy/10-org.nomachine.allow.system-sources-refresh.pkla" "/etc/polkit-1/localauthority/55-org.nomachine.d/"
      fi

      #
      # Only for ubuntu 15.04.
      #

      if [ "x${ubuntu_major}" = "x15" ] && [ "x${ubuntu_minor}" = "x04" ]
      then
        "${CPCOMMAND}" "${NX_ROOT}/share/policy/10-org.nomachine.allow.change-own-user-data.pkla" "/etc/polkit-1/localauthority/55-org.nomachine.d/"
      fi

      #
      # Only for KDE Neon since 5.22.
      #

      is_kde_system=""
      kde_neon_version=""

      if [ -f /etc/os-release ]
      then
        is_kde_system=$(${GREPCOMMAND} "KDE neon" /etc/os-release)

	if [ "${is_kde_system}x" != "x" ]
	then
	  kde_neon_version=$("${GREPCOMMAND}" "VERSION" "/etc/os-release" 2>/dev/null | \
	                     "${HEADCOMMAND}" -1 | "${CUTCOMMAND}" -d '=' -f 2 | \
                             "${SEDCOMMAND}" -nre 's/^[^0-9]*(([0-9]{1,}\.)*[0-9]{1,}).*/\1/p')

          kde_major=$(${ECHOCOMMAND} "${kde_neon_version}" | ${CUTCOMMAND} -d '.' -f1)
          kde_minor=$(${ECHOCOMMAND} "${kde_neon_version}" | ${CUTCOMMAND} -d '.' -f2)

	  if ([ ${kde_major} -eq 5 ] && [ ${kde_minor} -ge 22 ]) || [ ${kde_major} -gt 5 ]
	  then
	    "${CPCOMMAND}" "${NX_ROOT}/share/policy/10-org.nomachine.allow.network-control.pkla" "/etc/polkit-1/localauthority/55-org.nomachine.d/"
	  fi
	fi
      fi
    fi

    #
    # Installing polkit rule (.rules) files on polkit newer than 0.106.
    #

    if [ -e "$PKCHECKCOMMAND" ];
    then
      polkit_version=$(${PKCHECKCOMMAND} --version)

      if $("${ECHOCOMMAND}" "${polkit_version}" | "${GREPCOMMAND}" -q "\.")
      then
        polkit_version=$("${ECHOCOMMAND}" "${polkit_version}" | ${CUTCOMMAND} -d "." -f 2)
      else
        polkit_version=$("${ECHOCOMMAND}" "${polkit_version}" | ${CUTCOMMAND} -d " " -f 3-3)
      fi

      if [ $polkit_version -ge 106 ] && [ -d /usr/share/polkit-1/rules.d/ ]
      then
        "${CPCOMMAND}" "${NX_ROOT}/share/policy/55-org.nomachine.rules" "/usr/share/polkit-1/rules.d/"
      fi
    fi
  fi
}

uninstallPolkitFiles ()
{
  if [ "${system}" != "macosx" ];
  then
    if [ -d "/usr/share/polkit-1/actions/" ];
    then
      system_proxy_policy="org.freedesktop.packagekit.system-network-proxy-configure.policy"

      if [ -f "/usr/share/polkit-1/actions/${system_proxy_policy}" ]
      then
        compareMD5 "${NX_ROOT}/share/policy/${system_proxy_policy}" "/usr/share/polkit-1/actions/${system_proxy_policy}"

        if [ ${ret_compareMD5} -eq 1 ]
        then
          commandRm "/usr/share/polkit-1/actions/${system_proxy_policy}"
        fi
      fi
    fi

    #
    # Removing polkit rule (.pkla) file.
    #

    if [ -d /etc/polkit-1/localauthority/55-org.nomachine.d/ ]
    then
      commandRmIfExist "/etc/polkit-1/localauthority/55-org.nomachine.d/10-org.nomachine.allow.colord.pkla"
      commandRmIfExist "/etc/polkit-1/localauthority/55-org.nomachine.d/10-org.nomachine.allow.pcsc-lite.pkla"
      commandRmIfExist "/etc/polkit-1/localauthority/55-org.nomachine.d/10-org.nomachine.allow.change-own-user-data.pkla"
      commandRmIfExist "/etc/polkit-1/localauthority/55-org.nomachine.d/10-org.nomachine.allow.system-sources-refresh.pkla"

      commandRmDirIfExistEmpty "/etc/polkit-1/localauthority/55-org.nomachine.d/"
    fi
  fi
}

uncommentEnableScreenBlankingEffect ()
{
  setValueAtCfgFile "${CONFIG_FILE}" "EnableScreenBlankingEffect" "1"
}

procedureInstall ()
{
  unpackETCWrappers
  
  nxpreloadSetup

  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    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/nxrunner" --update ${SYSTEM}

	      if [ -f "${NX_ROOT}/scripts/setup/nxplayer" ] && [ -f "${NX_ETC_PLAYER}" ];
          then
            NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --update ${SYSTEM}
          fi
        else
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxrunner" --install ${SYSTEM}

	      if [ -f "${NX_ROOT}/scripts/setup/nxplayer" ] && [ -f "${NX_ETC_PLAYER}" ];
          then
            NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --install ${SYSTEM}
          fi
        fi

        NX_MPKG_PACKAGE="${PACKAGE_NAME}" NEW_LICENSE_ACRONYM="$NEW_LICENSE_ACRONYM" "${NX_ROOT}/scripts/setup/nxnode" --install ${SYSTEM}

        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/nxrunner" --update ${SYSTEM}

	if [ -f "${NX_ROOT}/scripts/setup/nxplayer" ] && [ -f "${NX_ETC_PLAYER}" ];
	then
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --update ${SYSTEM}
        fi
      else
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxrunner" --install ${SYSTEM}

        if [ -f "${NX_ROOT}/scripts/setup/nxplayer" ] && [ -f "${NX_ETC_PLAYER}" ];
        then
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --install ${SYSTEM}
        fi
      fi

      NX_MPKG_PACKAGE="${PACKAGE_NAME}" NEW_LICENSE_ACRONYM="$NEW_LICENSE_ACRONYM" "${NX_ROOT}/scripts/setup/nxnode" --install ${SYSTEM}
      return 0
    fi
  fi

  if [ "${system}" = "macosx" ];
  then
    if [ -f "${CONFIG_FILE}" ];
    then
      procedureUpdate
    fi
  fi

  initializeOperation "install"
  printOperationInfo  "install"

  setCatalinaUpper
  getPreviousVersion

  if [ "${system}" = "macosx" ];
  then
    if [ -d "${NX_ROOT}/var" ];
    then
      commandCpDir "${NX_ROOT}/var" "${NX_VAR_DIR}/../"
      commandRmDirRecursively "${NX_ROOT}/var"
    fi
  fi

  if [ "x$catalinaUpper" = "x1" ];
  then
    setEtcLink
  fi

  getPAMPath

  if [ -d "${ret_getPAMPath}" ];
  then
    pamScriptName=$(${BASENAMECOMMAND} "${NX_PAM_SCRIPT}" 2>&1)
    pamnxFile="${ret_getPAMPath}/${pamScriptName}"

    pamScriptName=""
    pamScriptName=$(${BASENAMECOMMAND} "${NX_PAM_SCRIPT_LIMITS}" 2>&1)
    pamnxlimitsFile="${ret_getPAMPath}/${pamScriptName}"
  fi

  if [ ! -f "${pamnxFile}" ];
  then
    installnxPAMScript
  fi

  if [ ! -f "${pamnxlimitsFile}" ];
  then
    installnxlimitsPAMScript
  fi

  addNXUser
  setUpdateCfg
  setAnywhereCfg
  setShell

  checkETCDirectory
  getSystemInfo

  installPolkitFiles

  if [ "x${NX_POSTINST}" != "x1" ];
  then
    makeNXConfig
  fi

  setConnectionMethods

  configureAgentApple
  createLogFiles

  removeSystemConfig

  checkCupsConfig
  setMultimedia
  nxPrintSetup
  setDefaultCommandXsession
  setAvailableSessionTypes
  setShareKey "install"

  updateConfigFile "install"

  if [ "${system}" != "macosx" ];
  then
    setPipeWireCommand
  fi

  enableNxUser

  setRestrictedPermissions
  setScriptsLogPermissions
  setScriptsEnvPermissions
  setEtcDirPermissions
  setVarDirPermissions

  fixTempXDir
  selinuxOperations
  if [ "${system}" = "solaris" ];
  then
    fixTempXDir__solaris
  fi

  if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
  then
    isInstalledMacPkg "server"
    if [ ${ret_isInstalledMacPkg} = 0 ];
    then
      runAgentApple
    fi
  fi

  upadetCommandsPath
  removeBlacklistedLlvmpipe

  addUpdateDBFile "1"

  fixCUDA

  isServerIncluded

  if [ "x${ret_isServerIncluded}" = "x1" ];
  then
    NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxserver" --install ${SYSTEM}
  fi

  printSummaryInfo "install"
  exit 0
}

package_files=(
/bin/nxnode
/bin/nxnode.bin
/bin/nxcodec.bin
/bin/nxagent
/bin/nxd
/bin/nxavc
/bin/nxlocate
/bin/nxcuinit
/etc/node-debian.cfg.sample
/etc/node-fedora.cfg.sample
/etc/node-mandriva.cfg.sample
/etc/node-redhat.cfg.sample
/etc/node-suse.cfg.sample
/etc/node-slackware.cfg.sample
/etc/node-solaris.cfg.sample
/etc/node-macosx.cfg.sample
/etc/node.cfg.tmp
/home/nx/.bash_logout
/home/nx/.bash_profile
/home/nx/.bashrc
/home/nx/.cache
/home/nx/.hushlogin
/home/nx/.Xauthority
/home/nx/.ssh/restore.id_dsa.pub
/home/nx/.ssh/default.id_dsa.pub
/home/nx/.ssh/restore.id_rsa.pub
/home/nx/.ssh/default.id_rsa.pub
"/home/nx/.cache/*"
/home/nx/.nx/ssh/server.id_dsa.key
/home/nx/.nx/ssh/server.id_rsa.key
/scripts/env/forcelogout.sh
/scripts/etc/localhost/node.cfg
/scripts/etc/nxnode
/scripts/etc/pam.d/nx
/scripts/etc/pam.d/nxlimits
/scripts/etc/pam.d/nx-legacy
/scripts/restricted/nxamixer.sh
/scripts/restricted/nxcookieget.sh
/scripts/restricted/nxenvironmentget.sh
/scripts/restricted/nxportandcookieget.sh
/scripts/restricted/nxkill.sh
/scripts/restricted/nxkeyadd.sh
/scripts/restricted/nxlicense.sh
/scripts/restricted/nxupdate.sh
/scripts/restricted/nxdisableAvc.sh
/scripts/restricted/nxsharedmem.sh
/scripts/restricted/nxtmpperm.sh
/scripts/restricted/nxuseradd.sh
/scripts/restricted/nxuserdel.sh
/scripts/restricted/nxloginctl.sh
/scripts/restricted/nxcopy.sh
/scripts/restricted/nxtruncate.sh
/scripts/setup/nxnode
/scripts/init/nxnode
/scripts/init/nxd
/scripts/systemd/${SYSTEMD_SENSOR_SERVICE}
/scripts/systemd/${SYSTEMD_NXD_SERVICE}
"/lib/libjsoncpp.so*"
"/lib/libminizip.so*"
"/lib/libnxau.so*"
"/lib/libnxcex.so*"
"/lib/libnxdi.so*"
"/lib/libnxdigl.so*"
"/lib/libnxdiag.so*"
"/lib/libnxdimi.so*"
"/lib/libnxh.so*"
"/lib/libnxhn.so*"
"/lib/libnxhs.so*"
"/lib/libnxhc.so*"
"/lib/libnxm.so*"
"/lib/libnxnws.so*"
"/lib/libx264.so*"
"/lib/libmfx.so*"
"/lib/libvpl.so*"
"/lib/pam_nxtoken.so*"
/lib/libcrypt.so.1
/lib/libcrypt-2.3.6.so
/lib/libsync.so
/lib/libvce14.so
/share/cursors
/share/images/nxagent.xpm
/share/documents/guides/NoMachine_Terminal_Server_Node_Installation_Guide.pdf
/share/documents/guides/Guide_to_the_Functionality_in_the_Menu_Panel_on_Linux.pdf
/share/documents/node/cups-info
/share/documents/node/audio-info
/share/documents/node/oss-info
/share/documents/node/license-info
/share/documents/node/credits.txt
/share/documents/node/readme-info
/share/documents/node/update-notices
/share/audio/client.conf
/share/audio/daemon.conf
/share/audio/default.pa
/share/audio/alsa.conf
"/share/keymaps/*"
/share/mac/launchd/com.nomachine.agent.plist
/share/policy/org.freedesktop.color.policy
/share/policy/org.freedesktop.color-manager.create-device.policy
/share/policy/org.freedesktop.packagekit.policy
/share/policy/org.freedesktop.packagekit.system-network-proxy-configure.policy
/share/policy/10-org.nomachine.allow.change-own-user-data.pkla
/share/policy/10-org.nomachine.allow.colord.pkla
/share/policy/10-org.nomachine.allow.pcsc-lite.pkla
/share/policy/10-org.nomachine.allow.system-sources-refresh.pkla
/lib/perl/Base64.so
/lib/perl/Cwd.so
/lib/perl/Fcntl.so
/lib/perl/HiRes.so
/lib/perl/Hostname.so
/lib/perl/IO.so
/lib/perl/libperl.so
/lib/perl/Linux.so
/lib/perl/MD5.so
/lib/perl/NXPL.so
/lib/perl/POSIX.so
/lib/perl/Resource.so
/lib/perl/Socket.so
/lib/perl/Solaris.so
/lib/perl/Syslog.so
/lib/perl/Util.so
/lib/perl/include/fcntl.ph
/lib/perl/include/features.ph
/lib/perl/include/_h2ph_pre.ph
/lib/perl/include/stddef.ph
/lib/perl/include/time.ph
/lib/perl/include/unistd_32.ph
/lib/perl/include/unistd_64.ph
/lib/perl/include/asm/unistd.ph
/lib/perl/include/asm/unistd_32.ph
/lib/perl/include/asm/unistd_64.ph
/lib/perl/include/auto/BSD/Resource/getrlimit.al
/lib/perl/include/auto/BSD/Resource/get_rlimits.al
/lib/perl/include/auto/BSD/Resource/setrlimit.al
/lib/perl/include/auto/DynaLoader/dl_findfile.al
/lib/perl/include/auto/POSIX/strerror.al
/lib/perl/include/auto/POSIX/getuid.al
/lib/perl/include/bits/fcntl.ph
/lib/perl/include/bits/pthreadtypes.ph
/lib/perl/include/bits/sched.ph
/lib/perl/include/bits/syscall.ph
/lib/perl/include/bits/types.ph
/lib/perl/include/bits/wordsize.ph
/lib/perl/include/Carp/Heavy.pm
/lib/perl/include/gnu/stubs.ph
/lib/perl/include/sys/cdefs.ph
/lib/perl/include/sys/fcntl.ph
/lib/perl/include/sys/syscall.ph
/lib/perl/include/sys/types.ph
/lib/perl/include/sys/wait.ph
/lib/perl/include/asm-i386/unistd.ph
/lib/perl/include/asm-i486/unistd.ph
/lib/perl/include/asm-x86_64/unistd.ph
)

package_directories_empty=(
/etc
/home/nx/.nx/ssh
/home/nx/.nx
/home/nx/.cache
/home/nx/.ssh
/home/nx
/home
/scripts/etc/pam.d
/scripts/init
/scripts/restricted
/scripts/setup
/scripts/systemd
/scripts
/share/documents/guides
/share/documents/node
/share/documents
/share/config
/share/branding/node
/share/branding
/share/images
/share/keymaps
/share/keymaps-windows
/share/audio
/share/mac/launchd
/share/mac
/share/policy
/share
/lib/perl/include/asm
/lib/perl/include/auto/BSD/Resource
/lib/perl/include/auto/BSD
/lib/perl/include/auto/DynaLoader
/lib/perl/include/auto/POSIX
/lib/perl/include/auto
/lib/perl/include/bits
/lib/perl/include/Carp
/lib/perl/include/gnu
/lib/perl/include/sys
/lib/perl/include/asm-i386
/lib/perl/include/asm-i486
/lib/perl/include/asm-x86_64
/lib/perl/include
/lib/perl
/lib
)

package_directories_recursive_before=(
/home/nx/.nx
)

package_directories_recursive=(
/share/layouts
/share/sounds
/share/applnk/node
/lib/perl/nxnode
/lib/perl
)

tab_lib_ver=(
libnxcex.so
libnxdigl.so
libnxdimi.so
)

processes_to_kill=(
nxnode.bin
nxnode
nxagent
nxd
nxavc
nxlocate
)

removeUnusedFiles ()
{
  commandRm "${NX_ROOT}/bin/nxuexec"

  commandRmIfExist "${NX_ROOT}/share/documents/node/baseline-info" "cmd"
  commandRmIfExist "${NX_ROOT}/share/documents/node/cups-info" "cmd"

  commandRmFiles "${NX_ROOT}/lib/libesddsp.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libesd.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libexpat.so.0" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libfreetype.so.6" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libX11.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXcompext.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXcomposite.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXcompshad.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXdamage.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXext.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXfixes.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXft.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXpm.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXrandr.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXrender.so" "cmd"
  commandRmFiles "${NX_ROOT}/lib/libXtst.so" "cmd"

  if [ -d "${NX_VAR_DIR}/run/printers" ];
  then
    commandRmDirRecursively "${NX_VAR_DIR}/run/printers" "cmd"
  fi
}

removeLeftovers()
{
  commandRmIfExist "${NX_ROOT}/share/config/knotifyrc.artsd" "cmd"
  commandRmIfExist "${NX_ROOT}/share/config/knotifyrc.esd" "cmd"
  commandRmIfExist "${NX_ROOT}/share/config/mcoprc" "cmd"

  if [ -d "${NX_ROOT}/share/config/skel-RedHat8.0" ];
  then
    commandRmDirRecursively "${NX_ROOT}/share/config/skel-RedHat8.0" "cmd"
  fi

  commandRmIfExist "${NX_ROOT}/scripts/restricted/nxgetcookie.sh" "cmd"
  commandRmIfExist "${NX_ROOT}/scripts/restricted/nxmountadd.sh" "cmd"
  commandRmIfExist "${NX_ROOT}/scripts/restricted/nxmountdel.sh" "cmd"
  commandRmIfExist "${NX_ROOT}/scripts/restricted/nxprinteradd.sh" "cmd"
  commandRmIfExist "${NX_ROOT}/scripts/restricted/nxprinterdel.sh" "cmd"

  commandRmIfExist "${NX_ROOT}/var/run/nxserver.pid"
  commandRmIfExist "${NX_ROOT}/var/run/nxserver.shutdown"
}

removeObsoleteFiles ()
{
  if [ "x${system}" = "xmacosx" ];
  then
    commandRmIfExist "${NX_ROOT}/lib/libnxhc.dylib" "cmd"
  else
    commandRmIfExist "${NX_ROOT}/lib/libnxhc.so" "cmd"
  fi
}

__installResources__ ()
{
  printMsgDebug "Installing node resources"
}

__installResourcesXDG__ ()
{
  printMsgDebug "Installing node resources XDG"

  install_xdg_ok=0

  if [ "x${NX_MPKG_PACKAGE}" != "x${PACKAGE_NAME}" ];
  then
    return 0
  fi

  installXDGMenu

  if [ $ret_installXDGMenu = 0 ];
  then
    printMsg "XDG installed properly" "cmd"
    install_xdg_ok=1
  else
    printMsg "Error while installing with XDG. Trying to install in a standard way" "warn"
  fi

  if [ $install_xdg_ok = 0 ];
  then
     __installResources__
  fi
}

__uninstallResources__ ()
{
  printMsgDebug "Uninstalling node resources"
}

__uninstallResourcesXDG__ ()
{
  uninstall_xdg_ok=0

  if [ "x${NX_MPKG_PACKAGE}" != "x${PACKAGE_NAME}" ];
  then
    return 0
  fi

  printMsg "Uninstalling with XDG" "cmd"
  uninstallXDGMenu

  if [ $ret_uninstallXDGMenu = 0 ];
  then
    printMsg "XDG uninstalled properly" "cmd"
    uninstall_xdg_ok=1
  else
    printMsg "Error while uninstalling with XDG. Trying to uninstall in standard way."
  fi

  if [ $uninstall_xdg_ok = 0 ];
  then
    __uninstallResources__
#  else
#    removeDesktopLinksForSolaris_player
  fi

}

procedureFinalUninstall ()
{

  commandRmDirRecursively "${NXHOME}" "cmd"
  commandRmDirIfExistEmpty "${NX_VAR_DIR}/run" "cmd"

  if [ "${system}" = "macosx" ];
  then

    if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
    then
      commandRmDirRecursively "${NX_ROOT}/bin/nxrunner.app" "cmd"
      commandRmDirIfExistEmpty "${NX_ROOT}/bin" "cmd"
      commandRmFiles "/var/db/receipts/com.nomachine.nomachineNode" "cmd"
      commandRmDirRecursively "${NX_ROOT}/lib" "cmd"

      #
      # for old versions (<=10.5)
      #

      commandRmDirRecursively "/Library/Receipts/nxrunner-${VERSION}-nc.pkg" "cmd"
      commandRmDirRecursively "/Library/Receipts/nxnode-${VERSION}-n.pkg" "cmd"
    fi
  fi
}

procedureUninstall ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then

    if [ "${system}" = "macosx" ];
    then
      if [ ${UID} -ne 0 ];
      then
        printMsg "Only root can run this script" "error"
        exit  1
      fi
      ret_getPackagePath=0
      ROOTDIR="${NX_ROOT}"
    else
      getPackagePath "${PACKAGE_NAME}"
    fi

    if [ ${ret_getPackagePath} = 0 ];
    then
      if [ "x${ROOTDIR}" = "x${NX_ROOT}" ];
      then
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxnode" --uninstall

        if [ -x "${NX_ROOT}/scripts/setup/nxplayer" ] && [ -f "${NX_ETC_PLAYER}" ];
        then
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --uninstall
        fi

        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxrunner" --uninstall

        removeInstallDir

        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"

  isServerIncluded
  if [ "x${ret_isServerIncluded}" = "x1" ];
  then
    NX_ETC_WEBPLAYER=/etc/NX/server/localhost/webplayer.cfg
    if [ -f "${NX_ETC_WEBPLAYER}" ] || [ -f "${NX_ROOT}/etc/cloud.cfg" ] || [ -f "${NX_ROOT}/etc/cloud.cfg.sample" ];
    then
      NX_MPKG_PACKAGE="server" "${NX_ROOT}/scripts/setup/nxwebplayer" --uninstall
    fi

    shutdownServer

    NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxserver" --uninstall
  fi

  printOperationInfo  "uninstall"

  uninstallPolkitFiles
  removePrintSetup
  removeSystemConfig
  resetPermissions
  removeETCDirectory
  resetNXConfig
  removeNXUser
  cleanRestrictedDirectory

  removePAMScript "nx"
  removePAMScript "nxlimits"

  if [ "${system}" = "macosx" ];
  then
    if [ "${NX_MPKG_PACKAGE}" = "server" ];
    then
      isInstalledMacPkg "node"

      if [ ${ret_isInstalledMacPkg} = 1 ];
      then
        configureAgentApple "node"
        runAgentApple
      else
        removeAgentFileApple
      fi

    elif [ "${NX_MPKG_PACKAGE}" = "node" ];
    then
      isInstalledMacPkg "server"

      if [ ${ret_isInstalledMacPkg} = 0 ];
      then
        removeAgentFileApple
      fi
    fi

    commandRm "${NX_ROOT}/../MacOS/nxuninstall" "warn"
  fi

  procedureFinalUninstall

  printSummaryInfo "uninstall"

  exit 0
}

uninstallPersonal ()
{
  NX_PERSONAL=1
  initializeOperation "uninstall"
  printOperationInfo  "uninstall"

  resetNXConfig
  removeETCDirectoryPersonal
  cleanPackageFiles

  printSummaryInfo "uninstall"

  exit 0
}

fixMissingCFGKeys ()
{
  if [ "${previous_version}x" = "5.1.40x" ] && [ -f ${CONFIG_FILE}.backup ]
  then

    config_lines=$(${WCCOMMAND} -l < "${CONFIG_FILE}")
    backup_config_lines=$(${WCCOMMAND} -l < "${CONFIG_FILE}.backup")
    last_command=$(${TAILCOMMAND} -n 5 "${CONFIG_FILE}")

    line_difference=$(( backup_config_lines - config_lines ))

    if [ ${line_difference} -gt 100 ] && [[ "${last_command}x" = *"CommandStartCDE"* ]]
    then
      ${CPCOMMAND} "${CONFIG_FILE}" "${CONFIG_FILE}.tmp"
      ${SEDCOMMAND} -n '/CommandStartCDE/,$p' "${CONFIG_FILE}.backup" | ${SEDCOMMAND} -e '1,2d' >> "${CONFIG_FILE}.tmp"
    fi

    commandRestoreFile "${CONFIG_FILE}" "tmp"

  fi
}

updateKDECommand ()
{
  oldkdeCommand="$("$GREPCOMMAND" "startkde" "$CONFIG_FILE" 2>/dev/null)"

  if [ "x$oldkdeCommand" != "x" ];
  then

    getStartplasmaSessionPath

    if [ -x "$ret_getStartplasmaSessionPath" ];
    then

      getStartkdeSessionPath

      if [ ! -x "$ret_getStartkdeSessionPath" ];
      then
        getDefaultKDECmd

        getValueFromCfgFile "DefaultDesktopCommand" "$CONFIG_FILE"
        if [ ${ret_getValueFromCfgFile} = 2 ];
        then
          if [[ "$cfg_val" == *"startkde"* ]];
          then
            setValueAtCfgFile "$CONFIG_FILE" "DefaultDesktopCommand" "$cmdKDE"
          fi
        fi

        getValueFromCfgFile "CommandStartKDE" "$CONFIG_FILE"
        if [ ${ret_getValueFromCfgFile} = 2 ];
        then
          if [[ "$cfg_val" == *"startkde"* ]];
          then
            setValueAtCfgFile "$CONFIG_FILE" "CommandStartKDE" "$cmdKDE"
          fi
        fi
      fi
    fi
  fi
}

moveNodeToServerLic ()
{
  OLD_LICENSE_FILE="${NX_ROOT}/etc/node.lic"

  if [ -f "$OLD_LICENSE_FILE" ] && [ ! -f "$LICENSE_FILE" ]
  then
    commandMv "$OLD_LICENSE_FILE" "$LICENSE_FILE" "error"

  elif [ -f "$OLD_LICENSE_FILE" ] && [ -f "$LICENSE_FILE" ]
  then
    commandMv "$OLD_LICENSE_FILE" "${OLD_LICENSE_FILE}.backup.old"
  fi
}

procedureUpdate ()
{
  if [ "$#" = 1 ];
  then
    if [ "${1}"x = "auto"x ];
    then
      updateType="auto"
    else
      updateType=""
    fi
  fi

  unpackETCWrappers

  nxpreloadSetup

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

    getLicenseAcronym "$LICENSE_FILE"

    if [[ "x${ret_getLicenseAcronym}" != *"LTSN"* ]]; then
      if [ "x${updateType}" = "xauto" ] || [ "x${UPDATETYPE}" = "xauto" ]; then
        "${NX_ROOT}/scripts/setup/nxserver" --update --auto
      else
        "${NX_ROOT}/scripts/setup/nxserver" --update
      fi

      return 0
    fi

    getPackagePath "${PACKAGE_NAME}"

    if [ ${ret_getPackagePath} = 0 ];
    then
      if [ "x${ROOTDIR}" = "x${NX_ROOT}" ];
      then

        NX_MPKG_PACKAGE="${PACKAGE_NAME}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxrunner" --update

        if [ -f "${NX_ROOT}/scripts/setup/nxplayer" ] && [ -f "${NX_ETC_PLAYER}" ];
        then
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxplayer" --update
        fi

        NX_MPKG_PACKAGE="${PACKAGE_NAME}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxnode" --update

        return 0
      else
        getProductName "${PACKAGE_NAME}"
        printMsg "${ret_getProductName} package is already installed in: ${ROOTDIR}"

        return 0
      fi
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxrunner" --update

      if [ -f "${NX_ROOT}/scripts/setup/nxplayer" ] && [ -f "${NX_ETC_PLAYER}" ];
      then
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxplayer" --update
      fi

      NX_MPKG_PACKAGE="${PACKAGE_NAME}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxnode" --update

      return 0
    fi
  fi

  initializeOperation "update"

  printOperationInfo  "update" "$upgrade"

  setCatalinaUpper
  getPreviousVersion

  if [ "${system}" = "macosx" ];
  then
    if [ -d "${NX_ROOT}/var" ];
    then
      commandRmDirRecursively "${NX_ROOT}/var"
    fi
  fi

  trueUpdate="0"

  if [ -f "$NX_ROOT/etc/trueUpdate" ];
  then
    trueUpdate="1"

    commandRm "$NX_ROOT/etc/trueUpdate"
  fi

  if [ "x$catalinaUpper" = "x1" ];
  then
    setEtcLink
  fi

  fixMissingCFGKeys

  if [ "x${UPDATETYPE}" = "xauto" ] &&
     [ -f "${NX_ROOT}/nomachine_automatic_update.deb" ] &&
     [ -f "${NX_ROOT}/nomachine_automatic_update.rpm" ];
  then
    installIncreaseVersionPackage
  fi

  getPAMPath

  if [ -d "${ret_getPAMPath}" ];
  then
    pamScriptName=$(${BASENAMECOMMAND} "${NX_PAM_SCRIPT}" 2>&1)
    pamnxFile="${ret_getPAMPath}/${pamScriptName}"

    pamScriptName=""
    pamScriptName=$(${BASENAMECOMMAND} "${NX_PAM_SCRIPT_LIMITS}" 2>&1)
    pamnxlimitsFile="${ret_getPAMPath}/${pamScriptName}"
  fi

  if [ ! -f "${pamnxFile}" ];
  then
    installnxPAMScript
  fi

  if [ ! -f "${pamnxlimitsFile}" ];
  then
    installnxlimitsPAMScript
  fi

  addNXUser
  setUpdateCfg
  setAnywhereCfg
  setShell

  makeConfBackup
  makeNXConfig

  installPolkitFiles

  enableNxUser
  createLogFiles

  configureAgentApple
  checkNXConfiguration
  checkETCDirectory
  setVarDirPermissions

  checkCupsConfig "update"
  updateDefaultCommandXsession

  setShareKey "update"

  removeSystemConfig
  updateConfigFile
  updateKDECommand
  updateUserScriptKeys

  if [ "x${upgrade}" = "x1" ];
  then
    setAvailableSessionTypes
  fi

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

  if [ "${system}" = "solaris" ];
  then
    fixTempXDir__solaris
  fi

  fixTempXDir
  selinuxOperations

  nxPrintSetup
  setMultimedia "update"
  setRestrictedPermissions
  setScriptsLogPermissions
  setScriptsEnvPermissions

  if [ "$upgrade" = "1" ];
  then
    removeUnusedFiles
  fi

  removeObsoleteFiles
  removeOldLibraries
  setEtcDirPermissions
  cleanShareDirectory
  removeLeftovers
  removeBlacklistedLlvmpipe

  fixDefaultDesktopCommand
  fixCUDA

  addUpdateDBFile "1"

  if [ "${UPDATETYPE}"x != "auto"x ];
  then
    checkStr=$("${NODE_ETC_SCRIPT}" --upgradecheck 2>&1)
    result=$(${ECHOCOMMAND} "$checkStr" | ${GREPCOMMAND} -c "expired" 2>&1)

    if [ "$result" != "0" ];
    then
      printMsgNoDot "Sorry, your upgrade period has expired. To be able to" "warn"
      printMsgNoDot "install a new version of the software, please visit the" "warn"
      printMsgNoDot "NoMachine Web site at http://www.nomachine.com/" "warn"
      printMsgNoDot "to acquire a valid subscription." "warn"
      exit 1
    fi
  fi

  if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
  then
    isInstalledMacPkg "server"

    if [ ${ret_isInstalledMacPkg} = 0 ];
    then
      runAgentApple
    fi
  fi

  if [ "x$trueUpdate" = "x1" ] && [ -f "$NX_ROOT/etc/server.lic.old" ] \
     && [ -f "$NX_ROOT/etc/node.lic.old" ];
  then
    trueUpdate="1"

    commandMv "$NX_ROOT/etc/server.lic.old" "$LICENSE_FILE" "cmd"
    commandMv "$NX_ROOT/etc/node.lic.old"   "$LICENSE_FILE" "cmd"
  fi

  isServerIncluded

  if [ "x${ret_isServerIncluded}" = "x1" ];
  then
    if [ -f "${NX_ROOT}/etc/server.cfg" ] || [ -f "${NX_ROOT}/etc/server.cfg.backup" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxserver" --update
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxserver" --install ${SYSTEM}
    fi
  fi

  printSummaryInfo "update"

  exit 0
}

procedureNxprintsetup ()
{
  if [ "x${LOGFILE}" = "x" ];
  then
    LOGFILE="${UPDATELOG}"
    createLogdirectory
    startLog
    PROCESS="${UPDATE}"
  fi

  if [ ! -r "${CONFIG_FILE}" ];
  then
    printMsg "ERROR: Cannot open: ${CONFIG_FILE}" "err"

    exit 1
  fi

  checkCupsConfig
  nxPrintSetup
  setNXaddprinterPermissions

  if [ "${SHOWCUPSINFO}" = "yes" ];
  then
    ${CATCOMMAND} "${NX_ROOT}/share/documents/node/cups-info"
  else
    printMsg "CUPS configuration updated" "cmd"
  fi
}

procedureAudioSetup ()
{
  audioConfPath="$1"

  if [ "x${LOGFILE}" = "x" ];
  then
    LOGFILE="$UPDATELOG"
    createLogdirectory
    startLog
    PROCESS="$UPDATE"
  fi

  if [ ! -r "${CONFIG_FILE}" ];
  then
    printMsg "ERROR: Cannot open file: ${CONFIG_FILE}" "error"
    exit 1
  fi

  if [ "$system" = "solaris" ];
  then
    checkOSS

  elif [ "$system" = "macosx" ];
  then
    setupKext "install" "nxaudio"
  else

    checkPipeWire

    if [ "$ret_checkPipeWire" = 0 ];
    then
      checkPulseAudio "setup" "$audioConfPath"

      if [ $ret_checkPulseAudio = 0 ];
      then
        printMsg "PulseAudio not found. Checking for: ALSA" "onlylog"
        checkAlsa
      fi
    fi
  fi
}

procedureVMwareSetup ()
{
  vmwarePath="$1"

  if [ ! -r "${CONFIG_FILE}" ];
  then
    printMsg "ERROR: Cannot open file: ${CONFIG_FILE}" "error"
    exit 1
  fi

  changeKeyAtConfigFile ${CONFIG_FILE} "VMWAREInstallPath" $vmwarePath

  printMsg "VMWAREInstallPath changed on: $vmwarePath"
}

addCustomeSessionsTypes ()
{
  if [ "x${previous_version}" != "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)

    if [[ ("${major_version}" -lt "4") || ("${major_version}" -le "4"  &&  "${minor_version}" -lt "4")
          || ("${major_version}" -le "4"  &&  "${minor_version}" -le "4" &&  "${maintenance_version}" -lt "10") ]];
    then

      custome_sessions_list="unix-console,unix-default,unix-application,"

      getAvailableSessionKey

      new_available_sessions_types="${custome_sessions_list}${available_sessions}"

      updateAvailableSessionKey "${new_available_sessions_types}"

      getAvailableSessionKey "${SERVER_USR_CONFIG_FILE}"

      new_available_sessions_types="${custome_sessions_list}${available_sessions}"

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

    fi
  fi
}

procedureAvailableSessionUpdate ()
{
  if [ "x${LOGFILE}" = "x" ];
  then
    LOGFILE="$UPDATELOG"
    createLogdirectory
    startLog
    PROCESS="$UPDATE"
  fi

  printMsg "Updating the AvailableSessionTypes key in: ${CONFIG_FILE}" "cmd"

  setAvailableSessionTypes

  CONFIG_FILE_BACKUP="${CONFIG_FILE}"

  CONFIG_FILE="${NX_ROOT}/etc/server.cfg"

  setAvailableSessionTypes

  CONFIG_FILE="${CONFIG_FILE_BACKUP}"
}

setAvailableSessionTypes ()
{

  if [ "${system}" != "macosx" ];
  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}"vpn,"

  availableSessionList=${availableSessionList%","*}

  updateAvailableSessionKey "$availableSessionList"
  #printMsgUpdatedKeyinConfigFile "AvailableSessionTypes" "$availableSessionList"
}

runActionPackage ()
{
  if [ "$action" = "--printingsetup" ];
  then
    printingsetupParm=$(${ECHOCOMMAND} "$printingsetupParm" | ${SEDCOMMAND} 's/^--//')

    if [ "x$printingsetupParm" != "x" ];
    then
      CUPS_PATH=( "${printingsetupParm}" )
    fi

    procedureNxprintsetup
  fi

  if [ "$action" = "--audiosetup" ];
  then
    audiosetupParm=$(${ECHOCOMMAND} "$audiosetupParm" | ${SEDCOMMAND} 's/^--//')
    procedureAudioSetup "$audiosetupParm"
  fi

  if [ "$action" = "--vmwaresetup" ];
  then
    vmwaresetupParm=$(${ECHOCOMMAND} "$vmwaresetupParm" | ${SEDCOMMAND} 's/^--//')
    procedureVMwareSetup "$vmwaresetupParm"
  fi

  if [ "$action" = "--osquery" ];
  then
    runActionOsquery
  fi

  if [ "$action" = "--sharingsetup" ];
  then
    sharingsetupParm=$(${ECHOCOMMAND} "$sharingsetupParm" | ${SEDCOMMAND} 's/^--//')
    if [ "x$sharingsetupParm" != "x" ];
    then
      SMB_PATH=( "$sharingsetupParm" )
      setShareKey "setup" "1"
    else
      setShareKey
    fi
  fi

  if [ "$action" = "--availablesessionsetup" ];
  then
    procedureAvailableSessionUpdate
  fi

  if [ "$action" = "--fixcuda" ];
  then
    initializeLogFile
    fixCUDA
    ${ECHOCOMMAND} "NX> 704 Running CUDA initialization procedure"
  fi
}

#
# Functions moved from nxserver to handle NX user
#

setPermUserNXHome ()
{
  commandChownR "${USER_NX}:${ROOTGNAME}" "${NXHOME}"
  commandChmod "0700" "${NXHOME}"
  setSELinuxContext "user_home_dir_t" "${NXHOME}"
}

addNXUserSolaris ()
{
  runCommand "$USERADDCOMMAND -d '${NXHOME}' -s '/etc/NX/nxnode' ${USER_NX}" "Cannot add user: ${USER_NX} to the system" "error"
}

addNXUserMac ()
{
  NX_USER="${USER_NX}"
  FULLNAME="NX user"
  NX_GROUP="${USER_NX}"
  ret_addNXUserMac=0

  if [ ${UID} -ne 0 ];
  then
    printMsg "Only root can add user: ${NX_USER}" "error"
    ret_addNXUserMac=1

    return 0
  fi

  out_id=$(${IDCOMMAND} -u ${NX_USER}  > /dev/null 2>&1)
  id_nx=$?

  if [ "x${id_nx}" = "x0" ];
  then
    printMsg "User: ${NX_USER} already exists" "warn"

    return 0
  fi

  for (( uid = 499;; --uid ));
  do
    if ! id -u $uid &>/dev/null;
    then
      USERID=$uid
      break
    fi

    if [ "x${uid}" = "x1" ] ;
    then
      MAXID=$(${DSCLCOMMAND} . -list /Users UniqueID | ${AWKCOMMAND} '{print $2}' | sort -ug | ${TAILCOMMAND} -1)
      USERID=$((MAXID+1))
      break
    fi
  done

  runCommand "${DSCLCOMMAND} . -create /Users/${NX_USER} IsHidden 1" "Cannot add user: ${NX_USER} to the system" "cmd"
  runCommand "${DSCLCOMMAND} . -append /Users/${NX_USER} AuthenticationAuthority ';SecureToken;'" "cmd"

  if [ ${ret_runCommand} != 0 ];
  then
    ret_addNXUserMac=1

    return 0
  fi

  printMsg "User: ${NX_USER} added to the system" "cmd"

  GROUP_ID=$(${DSCLCOMMAND} . -read /Groups/${NX_GROUP} PrimaryGroupID | ${AWKCOMMAND} '{print $2;}')

  runCommand "${DSCLCOMMAND} . -create /Users/${NX_USER} UserShell ${BASHSHELL}"\
                 "Cannot set shell for user '${NX_USER}' to '${BASHSHELL}'." "warn"

  runCommand "${DSCLCOMMAND} . -create /Users/${NX_USER} UniqueID ${USERID}"\
                 "Cannot set userID for user '${NX_USER}' to '${USERID}'" "warn"

  runCommand "${DSCLCOMMAND} . -create /Users/${NX_USER} PrimaryGroupID ${GROUP_ID}"\
                 "Cannot set groupID for user '${NX_USER}' to '${GROUP_ID}'" "warn"

  commandMkDir "$NXHOME"

  runCommand "${DSCLCOMMAND} . -create /Users/${NX_USER} NFSHomeDirectory '${NXHOME}'"\
                 "Cannot set home directory for user '${NX_USER}' to '${NXHOME}'" "warn"

  runCommand "${DSCLCOMMAND} . -create /Users/${NX_USER} RealName '${NX_USER}'"\
                 "Cannot set real name for user '${NX_USER}' to '${NX_USER}'" "warn"

  runCommand "${DSCLCOMMAND} . -create /Users/${NX_USER} RecordName '${NX_USER}' '${NX_USER}'"\
                 "Cannot set record name for user '${NX_USER}' to '${NX_USER}'" "warn"

  runCommand "${DSCLCOMMAND} . -delete /Users/${NX_USER} AuthenticationAuthority"\
                 "Cannot delete authentication authority for user '${NX_USER}'" "warn"

  runCommand "${DSCLCOMMAND} . -delete /Users/${NX_USER} PasswordPolicyOptions"\
                 "Cannot delete password policy options for user '${NX_USER}'" "warn"

  commandChmod "0700" "${NXHOME}"

  hideMacUser "${NX_USER}"

  addUserMacToSSHGroup "${NX_USER}"
  disableSptlightIndexing "${NX_USER}"
}

enableNxUser ()
{
  if [ "${system}" = "solaris" ];
  then
    command="/etc/NX/nxnode --enablenxuser"
    printMsg "Running: ${command}" "cmd"
    outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

    if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "cmd"
      printMsg "Cannot unlock account for user: ${USER_NX}" "error"
      runCommand "${USERDELCOMMAND} ${USER_NX}" "Cannot delete user: ${USER_NX} from the system" "error"

      exit 1
    else
      printMsgNoDot "Result: ${outCommand}" "cmd"
    fi

    commandChownR "${USER_NX}:root" "${NX_ROOT}/home/${USER_NX}"
    commandChmod "0700" "${NX_ROOT}/home/${USER_NX}"
  fi
}

setShellUserSolaris ()
{
  command="passwd -d ${USER_NX}"
  printMsg "Command: ${command}" "cmd"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ "$?" != 0 ];
  then
    printMsg "${outCommand}" "cmd"
    printMsg "Cannot unlock account for user: ${USER_NX}" "error"
    runCommand "${USERDELCOMMAND} ${USER_NX}" "Cannot delete user: ${USER_NX} from the system" "error"

    exit 1
  else
    printMsg "${outCommand}" "cmd"
    printMsg "Result: OK" "cmd"
  fi
}

setShellUserMac ()
{
  if [ "${NX_MPKG_PACKAGE}" = "node" ];
  then
    return 0
  fi

  checkNXUserExist

  if [ "x${ret_checkNXUserExist}" = "x1" ];
  then
    out=$(${DSCLCOMMAND} . -read /Users/${USER_NX} | ${GREPCOMMAND} UserShell | ${CUTCOMMAND} -d ' ' -f 2)

    if [ "$out" != "${NXSHELL}" ];
    then
      runCommand "${DSCLCOMMAND} . -create /Users/${USER_NX} UserShell '${NXSHELL}'"\
                     "Cannot set shell for user: ${USER_NX} to ${NXSHELL}" "error"
    fi
  else
    printMsg "User: ${USER_NX} doesn't exist" "error"
  fi
}


setShell ()
{
  if [ "x${system}" = "xsolaris" ];
  then
    setShellUserSolaris
  elif [ "x${system}" = "xmacosx" ];
  then
    setShellUserMac
  fi
}

setShellUserLinux ()
{
  command="${USERMODCOMMAND} -s '${NXSHELL}' ${USER_NX}"
  printMsg "Command: ${command}" "cmd"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ "$?" != 0 ];
  then
    printMsg "${outCommand}" "cmd"
    printMsg "Cannot set shell for user: ${USER_NX} to: ${NXSHELL}" "error"
    runCommand "${USERDELCOMMAND} ${USER_NX}" "Cannot delete user: ${USER_NX} from the system" "error"

    exit 1
  else
    printMsg "${outCommand}" "cmd"
    printMsg "Result: OK" "cmd"
  fi
}

removeNXUser ()
{
  result=$(${IDCOMMAND} ${USER_NX} 2>&1)

  if [ $? = 0 ];
  then
    if [ "${system}" = "macosx" ];
    then
      packageAppleDepend="server"
      packagePath="Service"

      if [ "x${NX_MPKG_PACKAGE}" = "xserver" ];
      then
        packageAppleDepend="node"
        packagePath="Node"
      fi

      isInstalledMacPkg "${packageAppleDepend}"

      if [ ${ret_isInstalledMacPkg} = 0 ];
      then
        removeNXUserApple "${USER_NX}"
      else
        printMsg "Found package: ${packageAppleDepend}. Skipping procedure to remove user: ${USER_NX}" "onlylog"

        if [ "x${NX_MPKG_PACKAGE}" = "xserver" ];
        then
          runCommand "${DSCLCOMMAND} . -create /Users/${USER_NX} UserShell ${BASHSHELL}"\
                         "Cannot set shell for user '${NX_USER}' to '${BASHSHELL}'." "warn"
        fi
      fi
      return 0
    fi

    if [ "${system}" != "solaris" ];
    then
      printMsg "Removing processes of user: ${USER_NX}" "cmd"

      TIMEOUTCOMMAND=""

      if [ "x$system" != "xmacosx" ];
      then
        if [ -x "/bin/timeout" ];
        then
          TIMEOUTCOMMAND="/bin/timeout"
        elif [ -x "/usr/bin/timeout" ];
        then
          TIMEOUTCOMMAND="/usr/bin/timeout"
        elif [ -x "/usr/sbin/timeout" ];
        then
          TIMEOUTCOMMAND="/usr/sbin/timeout"
        fi

        if [ "x$TIMEOUTCOMMAND" != "x" ];
        then
          TIMEOUTCOMMAND="$TIMEOUTCOMMAND 150"
        fi
      fi
      
      kill_out=$($TIMEOUTCOMMAND ${KILLALLCOMMAND} --wait --user ${USER_NX} 2>/dev/null)

      if [ "x${kill_out}" != "x" ];
      then
        printMsg "Output of kill command: ${kill_out}" "cmd"
      fi
    fi

    isNetworkUser "${USER_NX}"

    if [ ${ret_isNetworkUser} != 0 ];
    then
      printMsg "Skipping deleting user: ${USER_NX}: ${networkUserType} user"

      return 0
    fi

    printMsg "Deleting user: ${USER_NX} from the system" "cmd"

    result=$(${USERDELCOMMAND} ${USER_NX} 2>&1)
    resultCode=$?

    if [ $resultCode != 0 ];
    then
      checkNxhtdUserExist

      if [ "x${ret_checkNxhtdUserExist}" = "x0" ];
      then
        resultCode=0
      fi
    fi

    if [ $resultCode != 0 ];
    then
      result=$($USERDELCOMMAND ${user_htd} 2>&1)

      checkNxhtdUserExist
      resultCode=${ret_checkNxhtdUserExist}
    fi

    if [ ${resultCode} != 0 ];
    then
      printMsg "Cannot delete user: ${USER_NX} from the system"

      outputlog=$(${ECHOCOMMAND} ${result} | ${SEDCOMMAND} -e 's/userdel: //')
      printMsgNoDot "Reason is: ${outputlog}"

      if [ ${resultCode} = 1 ];
      then
        printMsgNoDot "Please, ensure that all programs preventing access"
        printMsgNoDot "to the password file are terminated, then run the"
        printMsgNoDot "command: userdel ${USER_NX}"

      elif [ ${resultCode} = 8 ];
      then
        printMsgNoDot "Please, ensure that all programs run by the ${USER_NX} user "
        printMsgNoDot "are terminated, then run the command: userdel ${USER_NX}"

      elif [ ${resultCode} = 10 ];
      then
        printMsgNoDot "Please, ensure that all programs preventing access"
        printMsgNoDot "to the group file are terminated, then run the"
        printMsgNoDot "command: userdel ${USER_NX}"

      elif [ ${resultCode} = 12 ];
      then
        printMsgNoDot "Please, ensure that all programs preventing access"
        printMsgNoDot "to the home directory are terminated, then run the"
        printMsgNoDot "command: userdel ${USER_NX}"
      fi
    fi
  else
    printMsg "User: ${USER_NX} already deleted from the system"
  fi
}

addUserNXSSHKey ()
{
  if [ ! -d "${NXHOME}/.nx/ssh" ];
  then
    commandMkDir "${NXHOME}/.nx/ssh/" "error"
  fi

  if [ ! -f "${currentDSAKey}" ];
  then
    runCommand "${CPCOMMAND} '${NX_ROOT}/share/keys/server.id_dsa.key' '$NXHOME/.nx/ssh/'"\
                   "Cannot copy file: ${NX_ROOT}/share/keys/server.id_dsa.key to: '${NXHOME}/.nx/ssh/'" "error"
  fi

  if [ ! -f "${currentRSAKey}" ];
  then
    runCommand "${CPCOMMAND} '${NX_ROOT}/share/keys/server.id_rsa.key' '$NXHOME/.nx/ssh/'"\
                   "Cannot copy file: ${NX_ROOT}/share/keys/server.id_rsa.key to: '${NXHOME}/.nx/ssh/'" "error"
  fi

  commandChmod "0400" "${currentDSAKey}" "error"
  commandChmod "0400" "${currentRSAKey}" "error"
  commandChownR "${USER_NX}:${ROOTGNAME}" "${NXHOME}/.nx" "error"
}

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

  package_name=$1

  if [ "x${package_name}" = "x" ] || [ "x${NX_MPKG_PACKAGE}" = "x${package_name}" ];
  then
    if [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
    then
      isInstalledMacPkg "server"

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

    path="${NX_ROOT}"
  else
    isInstalledMacPkg "${package_name}"
    if [ ${ret_isInstalledMacPkg} = 0 ];
    then
      return 0
    else
      getPackagePath "${package_name}"
      path="${ret_packagePath}"
    fi
  fi

  removeAgentFileApple

  ver=$(${SWVERSCOMMAND} | ${GREPCOMMAND} 'ProductVersion:' | ${AWKCOMMAND} -F '\.' '{print $2}')
}

removeAgentFileApple ()
{
  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 " unload -S\
                                        Aqua /Library/LaunchAgents/com.nomachine.agent.plist")}')

      for ((i=0;i<${#runAgentApple_command[@]};i++))
      do
        runCommand "${runAgentApple_command[${i}]}"\
                       "Cannot unload launchd nxagent file: /Library/LaunchAgents/com.nomachine.agent.plist" "error"
      done

    else

      while true
      do
        user=$(${PSCOMMAND} aux | ${GREPCOMMAND} "nxagent -M" | ${GREPCOMMAND} -v grep\
                 | ${GREPCOMMAND} -m 1 "nxagent -M" | ${AWKCOMMAND} '{print $1}')

        if [ "x${user}" = "x" ];
        then
          break
        fi

        if [ "x${user}" = "xroot" ];
        then
          runAgentApple_command="${SUCOMMAND} -l ${user} -c '${LAUNCHCTLCOMMAND} unload -S\
                                    LoginWindow /Library/LaunchAgents/com.nomachine.agent.plist'"
        else
          runAgentApple_command="${SUCOMMAND} -l ${user} -c '${LAUNCHCTLCOMMAND} unload -S\
                                    Aqua /Library/LaunchAgents/com.nomachine.agent.plist'"
        fi

        out=$(${BASHSHELL} -c "${runAgentApple_command}" 2>&1)

        if [ "x${out}" = "x" ];
        then
          out="OK"
        fi

        printMsg "Running: ${runAgentApple_command}" "cmd"
        printMsg "Result: ${out}" "cmd"
      done

      runAgentApple_command="${LAUNCHCTLCOMMAND} remove com.nomachine.agent"
      out=$(${BASHSHELL} -c "${runAgentApple_command}" 2>&1)

      if [ "x${out}" = "x" ];
      then
        out="OK"
      fi

      printMsg "Running: ${runAgentApple_command}" "cmd"
    fi

    commandRm "/Library/LaunchAgents/com.nomachine.agent.plist"
  fi
}

removePkgAppleFromDB ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "xconnect" ];
  then
    commandRm "/var/db/receipts/com.nomachine.nxconnect.*" "cmd"
  fi
}


makeConfBackup ()
{
  if [ -f "${CONFIG_FILE}" ];
  then
    printMsg "Saving configuration file to: ${CONFIG_FILE}.backup" "cmd"
    commandBackupFile "${CONFIG_FILE}" "backup" "error"
  fi
}

getRDPSessionPath ()
{
  RDP_SESSION_PATH=""

  command="${WHICHCOMMAND} xfreerdp 2>/dev/null | ${HEADCOMMAND} -1"
  command_out=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ -x "${command_out}" ];
  then
    RDP_SESSION_PATH="${command_out}"
    return 0
  fi

  command="${WHICHCOMMAND} rdesktop 2>/dev/null | ${HEADCOMMAND} -1"
  command_out=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ -x "${command_out}" ];
  then
    RDP_SESSION_PATH="${command_out}"
    return 0
  fi

  if [ -x "/usr/bin/xfreerdp" ];
  then
    RDP_SESSION_PATH="/usr/bin/xfreerdp"

  elif [ -x "/usr/bin/rdesktop" ];
  then
    RDP_SESSION_PATH="/usr/bin/rdesktop"

  elif [ -x "/bin/rdesktop" ];
  then
    RDP_SESSION_PATH="/bin/rdesktop"

  elif [ -x "/usr/local/bin/rdesktop" ];
  then
    RDP_SESSION_PATH="/usr/local/bin/rdesktop"

  fi
}

getVNCSessionPath ()
{
  VNC_SESSION_PATH=""

  command="${WHICHCOMMAND} vncviewer 2>/dev/null | ${HEADCOMMAND} -1"
  command_out=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ -x "${command_out}" ];
  then
    VNC_SESSION_PATH="${command_out}"
    return 0
  fi

  if [ -x "/usr/bin/vncviewer" ];
  then
    VNC_SESSION_PATH="/usr/bin/vncviewer"

  elif [ -x "/bin/vncviewer" ];
  then
    VNC_SESSION_PATH="/bin/vncviewer"

  elif [ -x "/usr/local/bin/vncviewer" ];
  then
    VNC_SESSION_PATH="/usr/local/bin/vncviewer"

  fi
}

getKDESessionPath ()
{
  KDE_SESSION_PATH=""

  getStartplasmaSessionPath

  if [ "x$ret_getStartplasmaSessionPath" != "x" ];
  then
    KDE_SESSION_PATH="$ret_getStartplasmaSessionPath"
  else
    getStartkdeSessionPath
    KDE_SESSION_PATH="$ret_getStartkdeSessionPath"
  fi
}

getStartkdeSessionPath ()
{
  ret_getStartkdeSessionPath=""

  command="${WHICHCOMMAND} startkde 2>/dev/null | ${HEADCOMMAND} -1"
  command_out=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ -x "${command_out}" ];
  then
    ret_getStartkdeSessionPath="${command_out}"

  elif [ -x "/usr/bin/startkde" ];
  then
    ret_getStartkdeSessionPath="/usr/bin/startkde"

  elif [ -x "/bin/startkde" ];
  then
    ret_getStartkdeSessionPath="/bin/startkde"

  elif [ -x "/usr/local/bin/startkde" ];
  then
    ret_getStartkdeSessionPath="/usr/local/bin/startkde"

  fi
}

getStartplasmaSessionPath ()
{
  ret_getStartplasmaSessionPath=""

  command="${WHICHCOMMAND} startplasma-x11 2>/dev/null | ${HEADCOMMAND} -1"
  command_out=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ -x "${command_out}" ];
  then
    ret_getStartplasmaSessionPath="${command_out}"

  elif [ -x "/usr/bin/startplasma-x11" ];
  then
    ret_getStartplasmaSessionPath="/usr/bin/startplasma-x11"

  fi
}

getGnomeSessionPath ()
{
  GNOME_SESSION_PATH=""

  command="${WHICHCOMMAND} gnome-session 2>/dev/null | ${HEADCOMMAND} -1"
  command_out=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ -x "${command_out}" ];
  then
    GNOME_SESSION_PATH="${command_out}"

  elif [ -x "/usr/bin/gnome-session" ];
  then
    GNOME_SESSION_PATH="/usr/bin/gnome-session"

  elif [ -x "/bin/gnome-session" ];
  then
    GNOME_SESSION_PATH="/bin/gnome-session"

  elif [ -x "/usr/local/bin/gnome-session" ];
  then
    GNOME_SESSION_PATH="/usr/local/bin/gnome-session"

  fi
}

getGnomeSessionsType ()
{
  GNOME_SESSION_TYPE=""

  unityEnabled="1";

  if [ "$system" = "ubuntu" ];
  then

    getUbuntuVersion

    ubuMajorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | ${CUTCOMMAND} -d '.' -f1)
    ubuMinorRel=$(${ECHOCOMMAND} "${ret_ubuntuVersion}" | ${CUTCOMMAND} -d '.' -f2)

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

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

    if [[ ("${ubuMajorRel}" -lt "12") || ("${ubuMajorRel}" -eq "12"  &&  "${ubuMinorRel}" -eq "4") ]];
    then
      unityEnabled="0";
    fi

  fi

  if [ -f /usr/share/gnome-session/sessions/ubuntu.session ] && [ "x${unityEnabled}" == "x1" ];
  then
    GNOME_SESSION_TYPE="ubuntu"

  elif [ -f /usr/share/gnome-session/sessions/ubuntu-2d.session ];
  then
    GNOME_SESSION_TYPE="ubuntu-2d"

  elif [ -f /usr/share/gnome-session/sessions/2d-ubuntu.session ];
  then
    GNOME_SESSION_TYPE="2d-ubuntu"
  elif [ -f /usr/share/gnome-session/sessions/pantheon.session ];
  then
    GNOME_SESSION_TYPE="pantheon"
  elif [ -f /usr/share/gnome-session/sessions/pop.session ];
  then
    GNOME_SESSION_TYPE="pop"
  elif [ -f /usr/share/gnome/gnome-version.xml ] && [ -f /usr/share/gnome-session/sessions/gnome.session ];
  then
    gnomeVersion=$("${GREPCOMMAND}" -e "<platform>3</platform>" -e "<platform>40</platform>" /usr/share/gnome/gnome-version.xml)

    if [ "x${gnomeVersion}" != "x" ];
    then
      GNOME_SESSION_TYPE="gnome"
    fi

  elif [ -f /usr/share/gnome-about/gnome-version.xml ] && [ -f /usr/share/gnome-session/sessions/gnome.session ];
  then
    gnomeVersion=$("${GREPCOMMAND}" -e "<platform>3</platform>" -e "<platform>40</platform>" /usr/share/gnome-about/gnome-version.xml)

    if [ "x${gnomeVersion}" != "x" ];
    then
      GNOME_SESSION_TYPE="gnome"
    fi

  elif [ -f /usr/share/gnome-session/sessions/gnome-classic.session ];
  then
    GNOME_SESSION_TYPE="gnome-classic"

  elif [ -f /usr/share/gnome-session/sessions/gnome-fallback.session ];
  then
    GNOME_SESSION_TYPE="gnome-fallback"
  fi
}

getGnomeSessionsTypeOld ()
{
  GNOME_SESSION_TYPE=""

  if [ -f /usr/share/gnome-session/sessions/ubuntu-2d.session ];
  then
    GNOME_SESSION_TYPE="ubuntu-2d"

  elif [ -f /usr/share/gnome-session/sessions/2d-ubuntu.session ];
  then
    GNOME_SESSION_TYPE="2d-ubuntu"

  elif [ -f /usr/share/gnome-session/sessions/gnome-classic.session ];
  then
    GNOME_SESSION_TYPE="gnome-classic"

  elif [ -f /usr/share/gnome-session/sessions/gnome-fallback.session ];
  then
    GNOME_SESSION_TYPE="gnome-fallback"
  fi
}

getGnomeCommandNewSuSE ()
{

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

    getSuSEVersion

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

    suseVersionMajor=$("${ECHOCOMMAND}" "${ret_suseVersion}" | "${CUTCOMMAND}" -d '.' -f 1)

    suseVersionMinor=$("${ECHOCOMMAND}" "${ret_suseVersion}" | "${CUTCOMMAND}" -d '.' -f 2)

    if [ "x${suseVersionMajor}" = "x" ] || [ "x${suseVersionMinor}" = "x" ];
    then
      return 0
    fi
    if [ -f /etc/os-release ]
      then
        SLED12=$(${GREPCOMMAND} "PRETTY_NAME" /etc/os-release)
    fi
    if [[ $( echo "$SLED12" | grep 'SUSE Linux Enterprise Desktop 12') ]];
    then

      COMMAND_GNOME_SESSION="env GNOME_SHELL_SESSION_MODE=sle-classic gnome-session --session sle-classic"
      GNOME_SESSION_PATH=""

      getGnomeSessionPath

    elif [[ ("${suseVersionMajor}" -gt "13")  || ("${suseVersionMajor}" -ge "13" && "${suseVersionMinor}" -ge "2") ]];
    then

      COMMAND_GNOME_SESSION=""
      GNOME_SESSION_PATH=""

      getGnomeSessionPath

      if [ "x${GNOME_SESSION_PATH}" != "x" ] && [ "x${DBUS}" = "x1" ] && [ "x${DBUS_PATH}" != "x" ];
      then

        getGnomeSessionsType

        if [ "x${GNOME_SESSION_TYPE}" != "x" ];
        then
          COMMAND_GNOME_SESSION="${DBUS_PATH} --exit-with-session gnome-session --session=${GNOME_SESSION_TYPE}"
        else
          COMMAND_GNOME_SESSION="${DBUS_PATH} --exit-with-session gnome-session"
        fi
      fi

    fi

  fi
}

getGnomeCommandSessionDebian ()
{
  if [ "x$system" = "xdebian" ];
  then

    COMMAND_GNOME_SESSION=""
    GNOME_SESSION_PATH=""

    getGnomeSessionPath

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

    getDistroVersion

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

    if [ "$DistroMajorRel" -ge 9 ] && [ "x$DBUS_PATH" != "x" ] && \
       [ "x$SSHAGENT_PATH" != "x" ];
    then
      COMMAND_GNOME_SESSION="$SSHAGENT_PATH $DBUS_PATH --exit-with-session x-session-manager"
    elif [ -f /etc/X11/Xsession ];
    then
      COMMAND_GNOME_SESSION="/etc/X11/Xsession gnome-session"
    elif [ -f /etc/gdm/Xsession ];
    then
      COMMAND_GNOME_SESSION="/etc/gdm/Xsession gnome-session"
    fi
  fi
}

getGnomeCommandSession ()
{
  COMMAND_GNOME_SESSION=""
  GNOME_SESSION_PATH=""

  getGnomeSessionPath
  if [ "x${GNOME_SESSION_PATH}" = "x" ];
  then
    return 0
  fi

  getGnomeSessionsType
  if [ "x${GNOME_SESSION_TYPE}" = "x" ];
  then
    return 0
  fi

  checkDBusLaunch

  getDistroVersion

  ubuMajorRel=$(${ECHOCOMMAND} "${ret_DistroVersion}" | ${CUTCOMMAND} -d '.' -f1)
  
  if [ "x${GNOME_SESSION_TYPE}" = "xubuntu" ] && [ "x$ret_checkDBusLaunch" != "x" ] && [ $ubuMajorRel -ge 22 ];
  then
    COMMAND_GNOME_SESSION="$ret_checkDBusLaunch gnome-session --session=ubuntu"
  elif [ "x${GNOME_SESSION_TYPE}" = "xubuntu" ] && [ -f /etc/X11/Xsession ];
  then
    COMMAND_GNOME_SESSION="/etc/X11/Xsession \'gnome-session --session=ubuntu\'"
  elif [ "x${GNOME_SESSION_TYPE}" = "pop" ];
  then
    COMMAND_GNOME_SESSION="env XDG_CURRENT_DESKTOP=pop:GNOME env GNOME_SHELL_SESSION_MODE=pop gnome-session --session=pop"
  elif [ "x$ret_checkDBusLaunch" != "x" ];
  then
    COMMAND_GNOME_SESSION="$ret_checkDBusLaunch gnome-session --session=${GNOME_SESSION_TYPE}"
  elif [ "x${GNOME_SESSION_TYPE}" = "xgnome" ] && [ -f /etc/gdm/Xsession ];
  then
    COMMAND_GNOME_SESSION="/etc/gdm/Xsession \'gnome-session --session=gnome\'"
  elif [ "x${GNOME_SESSION_TYPE}" = "xgnome" ] && [ -f /etc/X11/Xsession ];
  then
    COMMAND_GNOME_SESSION="/etc/X11/Xsession \'gnome-session --session=gnome\'"
  else
    COMMAND_GNOME_SESSION="${GNOME_SESSION_PATH} --session=${GNOME_SESSION_TYPE}"
  fi
}

fixDefaultDesktopCommand ()
{
  if [ "x$system" = "xredhat" ] || [ "x$system" = "xubuntu" ];
  then

    getDistroVersion

    majorDistVer=$("$ECHOCOMMAND" "$ret_DistroVersion" | "$CUTCOMMAND" -d '.' -f1)
    minorDistVer=$("$ECHOCOMMAND" "$ret_DistroVersion" | "$CUTCOMMAND" -d '.' -f2)

    if [ "x$system" = "xredhat" ] && [ "x$majorDistVer" = "x9" ];
    then
      getValueFromCfgFile "DefaultDesktopCommand" "${CONFIG_FILE}"

      if [ "x$cfg_val" = "x/etc/gdm/Xsession gnome-session" ];
      then
        getGnomeCommandSession

        setValueAtCfgFile "$CONFIG_FILE" "DefaultDesktopCommand" "$COMMAND_GNOME_SESSION"
      fi
    fi

    if [ "x$system" = "xubuntu" ] && [ "x$majorDistVer" = "x22" ] && [ "x$minorDistVer" = "x4" ];
    then
      getValueFromCfgFile "DefaultDesktopCommand" "${CONFIG_FILE}"

      if [ "x$cfg_val" = "xdbus-launch --exit-with-session gnome-session --session=ubuntu" ];
      then

        isDbusAvailable

        if [ "x$DBUS" = "x0" ];
        then
          getGnomeCommandSession

          setValueAtCfgFile "$CONFIG_FILE" "DefaultDesktopCommand" "$COMMAND_GNOME_SESSION"
        fi
      fi

    fi

    
  fi  
}

getGnomeCommandSessionOld ()
{
  COMMAND_GNOME_SESSION=""
  GNOME_SESSION_PATH=""

  getGnomeSessionPath
  if [ "x${GNOME_SESSION_PATH}" = "x" ];
  then
    return 0
  fi

  getGnomeSessionsTypeOld
  if [ "x${GNOME_SESSION_TYPE}" = "x" ];
  then
    return 0
  fi

  COMMAND_GNOME_SESSION="${GNOME_SESSION_PATH} --session=${GNOME_SESSION_TYPE}"
}

removeBlacklistedLlvmpipe ()
{
  checkSLES

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

  getSuSEVersion

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

  suseVersionMajor=$("${ECHOCOMMAND}" "${ret_suseVersion}" | "${CUTCOMMAND}" -d '.' -f 1)

  if [ "x${suseVersionMajor}" = "x12" ];
  then
    llvmpipe_out=$(${GREPCOMMAND} "+llvmpipe\|-llvmpipe" /usr/share/gnome-session/hardware-compatibility 2>/dev/null)

    if [ "x${llvmpipe_out}" = "x" ];
    then
      "${ECHOCOMMAND}" "+llvmpipe" >> "/usr/share/gnome-session/hardware-compatibility"
    fi
  fi
}

runAction
