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


PACKAGE_NAME="server"
VERSION="9.2.18"
PRODUCT_NAME="NoMachine Server $VERSION"
CONFIG_VERSION="4.0"

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

CONFIG_FILE="$NX_ROOT/etc/server.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
}


NX_ETC_WEBPLAYER=/etc/NX/server/localhost/webplayer.cfg

LSREGISTERCOMMAND="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"

commandUnregisterApp ()
{
  local app="$1"
  local msgType="$2"

  if [ -x "$LSREGISTERCOMMAND" ];
  then
    runCommand "$LSREGISTERCOMMAND -u -R $app" "Cannot unregister app: $app" "$msgType"
    ret_commandUnregister=${ret_runCommand}
  else
    printMsg "Cannot find $$LSREGISTERCOMMAND" "$msgType"
  fi
}

commandRegisterApp ()
{
  local app="$1"
  local msgType="$2"

  if [ -x "$LSREGISTERCOMMAND" ];
  then
    runCommand "$LSREGISTERCOMMAND -f -R $app" "Cannot register app: $app" "$msgType"
    ret_commandRegister=${ret_runCommand}
    "$LSREGISTERCOMMAND" -f -R $app
  else
    printMsg "Cannot find $$LSREGISTERCOMMAND" "$msgType"
  fi
}

checkMd5Bundles ()
{
  if [ -f "${NX_ROOT}/etc/nxserver.md5" ];
  then
    runCommand "$CATCOMMAND ${NX_ROOT}/etc/nxserver.md5" "cmd"

    oldMd5="$outCommand"

    runCommand "$MD5SUMCOMMAND -q ${NX_ROOT}/bin/nxserver.app/Contents/MacOS/nxserver" \
               "Cannot check a MD5 hash of a bundle." "cmd"

    if [ "x$oldMd5" != "x$outCommand" ];
    then
      commandTccutilReset "Accessibility" "com.nomachine.nxserver" "cmd"
    fi
  fi
}

unloadPlist ()
{
  commandCp "${NX_ROOT}/share/mac/launchd/com.nomachine.localnxserver.plist" "/Library/LaunchAgents/com.nomachine.localnxserver.plist" "cmd"

  set -f
  IFS='
'

  for line in $("$PSCOMMAND" -ef | "$GREPCOMMAND" loginwindow.app | "$GREPCOMMAND" -v grep | "$AWKCOMMAND" -v cmdlaunch=$LAUNCHCTLCOMMAND '{print (cmdlaunch " asuser " $1 " " cmdlaunch " unload -F -S Aqua /Library/LaunchAgents/com.nomachine.localnxserver.plist")}');
  do
    printMsg "launchctl line: $line" "cmd"

    out=$("$ECHOCOMMAND" $line | "$GREPCOMMAND" -e "asuser root" -e "asuser 0" 2>/dev/null || test 1)

    if [ "x${out}" != "x" ];
    then
      line=$("$ECHOCOMMAND" $line | "$SEDCOMMAND" 's/Aqua/LoginWindow/')

      runCommand "$line" "Cannot unload localnxserver plist." "warn"

      if [ $? != 0 ];
      then
        line=$(echo $line | sed 's/LoginWindow/Aqua/')

	runCommand "$line" "Cannot unload localnxserver plist." "warn"

        if [ $? != 0 ];
        then
          printErrorLogMsg "Cannot remove: com.nomachine.localnxserver.plist: $out"
        fi
      fi
    else
      runCommand "$line" "Cannot unload localnxserver plist." "warn"

      if [ $? != 0 ];
      then
        printErrorLogMsg "Cannot remove: com.nomachine.localnxserver.plist: $out"
      fi
    fi
  done;

  unset IFS
  set +f
}

readAuthorizedFileKey ()
{
  if [ "x${system}" = "xsolaris" ];
  then
    FILE_AUTHORIZED_KEYS="${NXHOME}/.ssh/authorized_keys"
  else
    FILE_AUTHORIZED_KEYS="${NXHOME}/.ssh/authorized_keys2"
  fi

  FILE_AUTHORIZED_KEYS_ENABLED=0

  getValueFromCfgFile "SSHAuthorizedKeys" "${CONFIG_FILE}"
  if [ ${ret_getValueFromCfgFile} = 1 ];
  then
    FILE_AUTHORIZED_KEYS="${NXHOME}/.ssh/${cfg_val}"
  elif [ ${ret_getValueFromCfgFile} = 2 ];
  then
    FILE_AUTHORIZED_KEYS="${NXHOME}/.ssh/${cfg_val}"
    FILE_AUTHORIZED_KEYS_ENABLED=1
  fi
}

setupNXPath()
{
  LICENSE_FILE="${NX_ROOT}/etc/server.lic"
  NODE_LICENSE_FILE="${NX_ROOT}/etc/node.lic"

  WRAPPER="${NX_ROOT}/bin/nxexec"

  NXWTMPADDSH="${NX_ROOT}/scripts/restricted/nxwtmpadd.sh"
  NXWTMPDELSH="${NX_ROOT}/scripts/restricted/nxwtmpdel.sh"
  NXPASSWDSH="${NX_ROOT}/scripts/restricted/nxpasswd.sh"
  NXQUOTAADD="${NX_ROOT}/scripts/restricted/nxquotaadd.sh"
  #NXCONFIGURATIONSH="${NX_ROOT}/scripts/restricted/nxconfigure.sh"
  NXGROUPADDSH="${NX_ROOT}/scripts/restricted/nxgroupadd.sh"
  NXHOSTSH="${NX_ROOT}/scripts/restricted/nxhost.sh"
  NXPASSWDASK="${NX_ROOT}/scripts/nxpasswdask.sh"
  NXCHOWN="${NX_ROOT}/scripts/restricted/nxchown.sh"
  NXFWADD="${NX_ROOT}/scripts/restricted/nxfwadd.sh"
  NXFWDEL="${NX_ROOT}/scripts/restricted/nxfwdel.sh"
  NXFWGET="${NX_ROOT}/scripts/restricted/nxfwget.sh"
  NXCLUSTERMASTER="${NX_ROOT}/scripts/restricted/nxclustermaster.sh"
  NXSTANDBY="${NX_ROOT}/scripts/restricted/nxstandby.sh"
  NXSHUTDOWN="${NX_ROOT}/scripts/restricted/nxshutdown.sh"
  NXSYNCHRONIZE="${NX_ROOT}/scripts/restricted/nxsynchronize.sh"
  NXLAUNCHCTL="${NX_ROOT}/scripts/restricted/nxlaunchctl.sh"
  NXCAT="${NX_ROOT}/scripts/restricted/nxcat.sh"
  NXLSOF="${NX_ROOT}/scripts/restricted/nxlsof.sh"
  NXTAPDEL="${NX_ROOT}/scripts/restricted/nxtapdel.sh"
  NXTAPADD="${NX_ROOT}/scripts/restricted/nxtapadd.sh"
  NXGFXCHECK="${NX_ROOT}/scripts/restricted/nxgfxcheck.sh"
  NXRESTARTSH="${NX_ROOT}/scripts/restricted/nxrestart.sh"
  NXCHMOD="${NX_ROOT}/scripts/restricted/nxchmod.sh"
  NXRENICE="${NX_ROOT}/scripts/restricted/nxrenice.sh"
  NXSETSSHAGENT="${NX_ROOT}/scripts/restricted/nxsetsshagent.sh"
  NXDBUSMONITOR="${NX_ROOT}/scripts/restricted/nxdbusmonitor.sh"
  NXHTDCHOWN="${NX_ROOT}/scripts/restricted/nxhtdchown.sh"
  NXEGLEVENT="${NX_ROOT}/scripts/restricted/nxeglevent.sh"
  NXWEBHOSTCERTGET="${NX_ROOT}/scripts/restricted/nxwebhostcertget.sh"
  NXSSHHOSTCERTGET="${NX_ROOT}/scripts/restricted/nxsshhostcertget.sh"
  NXSSHHOSTCERTSET="${NX_ROOT}/scripts/restricted/nxsshhostcertset.sh"
  NXSSHHOSTCERTRESTORE="${NX_ROOT}/scripts/restricted/nxsshhostcertrestore.sh"
  NXCLUSTERSLAVE="${NX_ROOT}/scripts/restricted/nxclusterslave.sh"
  NXDEBUGCOLLECT="${NX_ROOT}/scripts/restricted/nxdebugcollect.sh"
  NXDISABLESERVICES="${NX_ROOT}/scripts/restricted/nxdisableservices.sh"
  NXENABLESERVICES="${NX_ROOT}/scripts/restricted/nxenableservices.sh"
  NXSSHRESTART="${NX_ROOT}/scripts/restricted/nxsshrestart.sh"

  NXROUTEIN="${NX_ROOT}/scripts/restricted/nxroutein.sh"
  NXROUTEINADD="${NX_ROOT}/scripts/restricted/nxrouteinadd.sh"
  NXROUTEINDEL="${NX_ROOT}/scripts/restricted/nxrouteindel.sh"

  NXSTOPSERVERFLAG="${NX_ROOT}/etc/stop-server"
  ENABLE_HTTP_CFG_KEY="StartHTTPDaemon"
  NXKEYGENCOMMAND="${NX_ROOT}/bin/nxkeygen"

  SYSTEMD_SERVER_SERVICE="nxserver.service"
  UPSTART_SERVER_SERVICE="nxserver"

  readAuthorizedFileKey

  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"

  SSHDPort="22"
}

setupNXPath ""

setAuthKey ()
{
  #
  # 1 - key to set (original)
  # 2 - key to set (current)
  #

  original="${1}"
  current="${2}"

  ret_setAuthKey=0

  if [ ! -f "${original}" ];
  then

    printMsg "Cannot find original key file: ${original}" "cmd"

    ret_setAuthKey=1

  else

    if [ ! -f "${current}" ]
    then

      runCommand "${CPCOMMAND} -fp '${original}' '${current}'" "Cannot set current key file: ${current}" "error"

      ret_setAuthKey=${ret_runCommand}
    fi
  fi
}

restoreOriginalAuthKey ()
{
  #
  # 1 - key to restore
  #

  restore="${NX_ROOT}/var/nx/.ssh/${1}"
  original="${NXHOME}/.ssh/${1}"

  ret_restoreOriginalAuthKey=0

  if [ ! -f "${original}" ];
  then
    if [ -f "${restore}" ];
    then
      runCommand "${CPCOMMAND} -fp '${restore}' '${original}'" "Cannot set original key file: ${original}" "error"
    else
      printMsg "Cannot find ${original} key file." "cmd"

      ret_restoreOriginalAuthKey=1
    fi
  fi
}

checkCustomAuthKey ()
{
  ret_checkCustomAuthKey=0

  if [ -f "${originalDSAKey}" ] && [ -f "${FILE_AUTHORIZED_KEYS}" ]
  then
    original=$(${CATCOMMAND} "${originalDSAKey}")
    authorized=$(${CATCOMMAND} "${FILE_AUTHORIZED_KEYS}")

    if [[ "${authorized}" != *"${original}"* ]]
    then
      ret_checkCustomAuthKey=1
    fi
  fi
}

addRSAToAuthorizedKey ()
{
  getPreviousVersion

  if ( [ ${major_version} -eq 5 ] && [ ${minor_version} -eq 1 ] && [ ${maintenance_version} -lt 21 ] ) ||
       ( [ ${major_version} -eq 5 ] && [ ${minor_version} -lt 1 ] ) ||
       ( [ ${major_version} -lt 5 ] )
  then
    checkCustomAuthKey

    if [ ${ret_checkCustomAuthKey} -eq 0 ]
    then
      isSSHSupported

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

        setAuthorizedKeyFileName

        if [ -f "${FILE_AUTHORIZED_KEYS}" ];
        then
          if [ ! -f "${currentRSAKey}" ];
          then
            runCommand "${CPCOMMAND} -p '${currentRSAKey}.backup' '${currentRSAKey}'" "Cannot restore RSA key." "warn"
          fi

          runCommand "${CATCOMMAND} '${currentRSAKey}' >> '${FILE_AUTHORIZED_KEYS}'" "Cannot add RSA key to {FILE_AUTHORIZED_KEYS}" "warn"

          setContextForAuthKeys
        fi
      fi
    fi
  fi
}

upgradeAuthorizedKey ()
{
  isSSHSupported

  setAuthorizedKeyFileName

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

  if [ -f "${FILE_AUTHORIZED_KEYS}" ];
  then
    commandRm "${FILE_AUTHORIZED_KEYS}" "warn"

    if [ ! -f "${currentRSAKey}" ];
    then
      runCommand "${CPCOMMAND} -p '${currentRSAKey}.backup' '${currentRSAKey}'" "Cannot restore RSA key." "warn"
    fi

    if [ ! -f "${currentDSAKey}" ];
    then
      runCommand "${CPCOMMAND} -p '${currentDSAKey}.backup' '${currentDSAKey}'" "Cannot restore RSA key." "warn"
    fi

    runCommand "${CPCOMMAND} -p '${currentRSAKey}' '${FILE_AUTHORIZED_KEYS}'" "Cannot start NoMachine Server" "warn"
    runCommand "${CATCOMMAND} '${currentDSAKey}' >> '${FILE_AUTHORIZED_KEYS}'" "Cannot start NoMachine Server" "warn"

    setContextForAuthKeys
  fi
}

updateAuthorizedKey ()
{
    if [ -f "${NXHOME}/.ssh/authorized_keys" ];
  then
    ${SEDCOMMAND} '/command=.*node/d' "${NXHOME}/.ssh/authorized_keys" > "${NXHOME}/.ssh/authorized_keys.tmp"

    commandRestoreFile "${NXHOME}/.ssh/authorized_keys" "tmp"
  fi

  if [ -f "${NXHOME}/.ssh/authorized_keys2" ];
  then
    ${SEDCOMMAND} '/command=.*node/d' "${NXHOME}/.ssh/authorized_keys2" > "${NXHOME}/.ssh/authorized_keys2.tmp"

    commandRestoreFile "${NXHOME}/.ssh/authorized_keys2" "tmp"
  fi

  #
  # Updating old key,
  # updating RSA not needed
  #

  if [ -f "${currentDSAKey}" ];
  then
    ${SEDCOMMAND} '/command=.*node/d' "${currentDSAKey}" > "${currentDSAKey}.tmp"

    commandRestoreFile "${currentDSAKey}" "tmp"
  fi
}

setAuthKeysPermissions ()
{
  if [ -f "${currentDSAKey}" ];
  then
    commandChmod "0600" "${currentDSAKey}"
  fi

  if [ -f "${originalDSAKey}" ];
  then
    commandChmod "0600" "${originalDSAKey}"
  fi

  if [ -f "${currentRSAKey}" ];
  then
    commandChmod "0600" "${currentRSAKey}"
  fi

  if [ -f "${originalRSAKey}" ];
  then
    commandChmod "0600" "${originalRSAKey}"
  fi
}

resetPermissionsServer ()
{
  if [ -f "${NXWTMPADDSH}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "755" "${NXWTMPADDSH}" "warn"
  fi

  if [ -f "${NXWTMPDELSH}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "755" "${NXWTMPDELSH}" "warn"
  fi

  if [ -f "${NXPASSWDSH}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXPASSWDSH}" "warn"
  fi

  if [ -f "${NXQUOTAADD}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXQUOTAADD}" "warn"
  fi

  if [ -f "${NXGROUPADDSH}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXGROUPADDSH}" "warn"
  fi

  if [ -f "${NXHOSTSH}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXHOSTSH}" "warn"
  fi

  if [ -f "${NXPASSWDASK}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "755" "${NXPASSWDASK}" "warn"
  fi

  if [ -f "${NXCHOWN}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXCHOWN}" "warn"
  fi

  if [ -f "${NXFWADD}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXFWADD}" "warn"
  fi

  if [ -f "${NXFWDEL}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXFWDEL}" "warn"
  fi

  if [ -f "${NXFWGET}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXFWGET}" "warn"
  fi

  if [ -f "${NXCLUSTERMASTER}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXCLUSTERMASTER}" "warn"
  fi

  if [ -f "${NXSTANDBY}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSTANDBY}" "warn"
  fi

  if [ -f "${NXSHUTDOWN}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSHUTDOWN}" "warn"
  fi

  if [ -f "${NXSYNCHRONIZE}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSYNCHRONIZE}" "warn"
  fi

  if [ -f "${NXCLUSTERSLAVE}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXCLUSTERSLAVE}" "warn"
  fi

  if [ -f "${NXDEBUGCOLLECT}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXDEBUGCOLLECT}" "warn"
  fi
  
  if [ -f "${NXLAUNCHCTL}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXLAUNCHCTL}" "warn"
  fi

  if [ -f "${NXCAT}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXCAT}" "warn"
  fi

  if [ -f "${NXLSOF}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXLSOF}" "warn"
  fi

  if [ -f "${NXTAPADD}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXTAPADD}" "warn"
  fi

  if [ -f "${NXTAPDEL}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXTAPDEL}" "warn"
  fi

  if [ -f "${NXGFXCHECK}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXGFXCHECK}" "warn"
  fi

  if [ -f "${NXRESTARTSH}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXRESTARTSH}" "warn"
  fi

  if [ -f "${NXCHMOD}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXCHMOD}" "warn"
  fi

  if [ -f "${NXRENICE}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXRENICE}" "warn"
  fi

  if [ -f "${NXSETSSHAGENT}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSETSSHAGENT}" "warn"
  fi

  if [ -f "${NXDBUSMONITOR}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXDBUSMONITOR}" "warn"
  fi

  if [ -f "${NXHTDCHOWN}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXHTDCHOWN}" "warn"
  fi

  if [ -f "${NXEGLEVENT}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXEGLEVENT}" "warn"
  fi

  if [ -f "${NXWEBHOSTCERTGET}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXWEBHOSTCERTGET}" "warn"
  fi

  if [ -f "${NXSSHHOSTCERTGET}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSSHHOSTCERTGET}" "warn"
  fi

  if [ -f "${NXSSHHOSTCERTSET}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSSHHOSTCERTSET}" "warn"
  fi

  if [ -f "${NXSSHHOSTCERTRESTORE}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSSHHOSTCERTRESTORE}" "warn"
  fi

  if [ -f "${NXROUTEIN}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "644" "${NXROUTEIN}" "warn"
  fi

  if [ -f "${NXROUTEINADD}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXROUTEINADD}" "warn"
  fi

  if [ -f "${NXROUTEINDEL}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXROUTEINDEL}" "warn"
  fi

  if [ -f "${NXDISABLESERVICES}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXDISABLESERVICES}" "warn"
  fi

  if [ -f "${NXENABLESERVICES}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXENABLESERVICES}" "warn"
  fi

  if [ -f "${NXSSHRESTART}" ];
  then
    commandChownChmod "root:${ROOTGNAME}" "744" "${NXSSHRESTART}" "warn"
  fi
}

checkSessregPath ()
{
  if [ ! -r "${CONFIG_FILE}" ];
  then
    return 1
  fi

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

  if [ $? != 0 ];
  then
    if [ "${system}" = "solaris" ];
    then

      ${ECHOCOMMAND} "#
# Sets path and name of the command 'sessreg'.
#
#CommandSessreg = \"/usr/X/bin/sessreg\"
">> "${CONFIG_FILE}"

    else

      ${ECHOCOMMAND} "#
# Sets path and name of the command 'sessreg'.
#
#CommandSessreg = \"/usr/X11/bin/sessreg\"
">> "${CONFIG_FILE}"

    fi
  fi
}

chownChmodSuid ()
{
  #
  # 1 - file
  #

  file="${1}"
  ret_chownChmodSuid=0

  if [ -f "${file}" ];
  then
    commandChownChmodSuid "root:${ROOTGNAME}" "744" "${file}" "error"
  else
    printMsg "No such file: ${file}" "error"

    ret_chownChmodSuid=1
  fi
}

setFail2banPermisions ()
{
  commandChmod "0644" "${NX_ROOT}/share/fail2ban/nxd.conf"
  commandChmod "0644" "${NX_ROOT}/share/fail2ban/nxauth.conf"
}

setNxsessregPermisions ()
{
  chownChmodSuid "${NXWTMPADDSH}"

  if [ ${ret_chownChmodSuid} = 1 ]
  then
    exit 1
  else
    chownChmodSuid "${NXWTMPDELSH}"

    if [ ${ret_chownChmodSuid} = 1 ]
    then
      exit 1
    fi
  fi
}

setNxUserMngshPermissions ()
{
  chownChmodSuid "${NXPASSWDSH}"

  if [ -f "${NXRESTARTSH}" ];
  then
    chownChmodSuid "${NXRESTARTSH}"
  fi

  if [ -f "${NXSYNCHRONIZE}" ]
  then
    chownChmodSuid "${NXSYNCHRONIZE}"
  fi

  if [ "x${system}" != "xmacosx" ];
  then
    chownChmodSuid "${NXHOSTSH}"
    chownChmodSuid "${NXFWADD}"
    chownChmodSuid "${NXFWDEL}"
    chownChmodSuid "${NXFWGET}"
    chownChmodSuid "${NXGROUPADDSH}"
    chownChmodSuid "${NXQUOTAADD}"
    chownChmodSuid "${NXLSOF}"
    chownChmodSuid "${NXGFXCHECK}"
    chownChmodSuid "${NXCHMOD}"
    chownChmodSuid "${NXRENICE}"
    chownChmodSuid "${NXSETSSHAGENT}"
    chownChmodSuid "${NXDBUSMONITOR}"
  fi

  if [ -f "${NXPASSWDASK}" ]
  then
    commandChownChmod "root:${ROOTGNAME}" "755" "${NXPASSWDASK}" "error"
  else
    printMsg "No such file: ${NXPASSWDASK}" "warn"
  fi

  chownChmodSuid "${NXCHOWN}"

  if [ -f "${NXHTDCHOWN}" ];
  then
    chownChmodSuid "${NXHTDCHOWN}"
  fi

  if [ -f "${NXEGLEVENT}" ];
  then
    chownChmodSuid "${NXEGLEVENT}"
  fi

  if [ -f "${NXWEBHOSTCERTGET}" ];
  then
    chownChmodSuid "${NXWEBHOSTCERTGET}"
  fi

  if [ -f "${NXSSHHOSTCERTGET}" ];
  then
    chownChmodSuid "${NXSSHHOSTCERTGET}"
  fi

  if [ -f "${NXSSHHOSTCERTSET}" ];
  then
    chownChmodSuid "${NXSSHHOSTCERTSET}"
  fi

  if [ -f "${NXSSHHOSTCERTRESTORE}" ];
  then
    chownChmodSuid "${NXSSHHOSTCERTRESTORE}"
  fi

  chownChmodSuid "${NXCAT}"

  if [ -f "${NXTAPADD}" ];
  then
    chownChmodSuid "${NXTAPADD}"
  fi

  if [ -f "${NXTAPDEL}" ];
  then
    chownChmodSuid "${NXTAPDEL}"
  fi

  if [ -f "${NXDISABLESERVICES}" ];
  then
    chownChmodSuid "${NXDISABLESERVICES}"
  fi

  if [ -f "${NXENABLESERVICES}" ];
  then
    chownChmodSuid "${NXENABLESERVICES}"
  fi

  if [ -f "${NXSSHRESTART}" ];
  then
    chownChmodSuid "${NXSSHRESTART}"
  fi

  chownChmodSuid "${NXCLUSTERMASTER}"
  chownChmodSuid "${NXSTANDBY}"
  chownChmodSuid "${NXSHUTDOWN}"
  chownChmodSuid "${NXCLUSTERSLAVE}"
  chownChmodSuid "${NXDEBUGCOLLECT}"

  chownChmodSuid "${NXROUTEINADD}"
  chownChmodSuid "${NXROUTEINDEL}"

  if [ "x${system}" != "xmacosx" ];
  then
    if [ -f "${NXROUTEIN}" ]
    then
      commandChownChmod "root:${ROOTGNAME}" "644" "${NXROUTEIN}" "error"
    else
      printMsg "No such file: ${NXROUTEIN}" "warn"
    fi
  fi

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

    if [ "x$catalinaUpper" = "x1" ];
    then
      if [ ! -h "$NXSHELL" ];
      then
        commandRm "$NXSHELL" "warn"
      fi

      if [ ! -f "$NXSHELL" ];
      then
        commandLn "${NX_ROOT}/bin/nxserver.app/Contents/MacOS/nxserver" "$NXSHELL" "error"
      fi
    fi
  fi

  if [ -f "${NXSHELL}" ]
  then
    if [ "x$catalinaUpper" = "x1" ];
    then
      commandChownChmod "${USER_NX}:${USER_NX}" "555" "${NXSHELL}" "error"
    else
      commandChownChmod "${USER_NX}:${USER_NX}" "6555" "${NXSHELL}" "error"
    fi
  else
    printMsg "No such file: ${NXSHELL}" "warn"
  fi
}

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
}

addNXserverConf ()
{
  commandRmIfExist "/etc/init/nxserver.conf" "warn"

  #
  # Checking initctl version.
  #  (Versions before 1.4 do not support suid and guid feature).
  #

  initctl_version=$("${INITCTLCOMMAND}" --version | "${GREPCOMMAND}" "upstart" | "${SEDCOMMAND}" 's/[[:alpha:]|(|[:space:]]//g' | "${CUTCOMMAND}" -d ")" -f -1)
  initctl_version_major=$("${ECHOCOMMAND}" "${initctl_version}" | "${CUTCOMMAND}" -d "." -f -1)
  initctl_version_minor=$("${ECHOCOMMAND}" "${initctl_version}" | "${CUTCOMMAND}" -d "." -f 2-2)

  if ([ "${initctl_version_major}" -eq 1 ] && [ "${initctl_version_minor}" -lt 14 ]) || [ "${initctl_version_major}" -lt 1 ]
  then
    ${SEDCOMMAND} -e 's:#USRNXDIR#:'"${NX_ROOT}"':' "${NX_ROOT}/scripts/init/nxserver.conf.legacy" > "${NX_ROOT}/scripts/init/nxserver.conf.legacy.tmp"

    commandRestoreFile "${NX_ROOT}/scripts/init/nxserver.conf.legacy" "tmp"

    commandInstall "root" "${ROOTGNAME}" "644" "${NX_ROOT}/scripts/init/nxserver.conf.legacy" \
                   "/etc/init/nxserver.conf"
  else
    commandInstall "root" "${ROOTGNAME}" "644" "${NX_ROOT}/scripts/init/nxserver.conf" \
                   "/etc/init/" "warn"
  fi
}

removeNXserverConf ()
{
  if [ "x${system}" = "xubuntu" ];
  then
    commandRmIfExist "/etc/init/nxserver.conf" "warn"
  fi
}

removeNXinit ()
{
  #
  # MacOS.
  #

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

    return 0
  fi

  #
  # Linux.
  #  SystemD.
  #

  isSystemDSupported

  if [ ${ret_isSystemDSupported} = 1 ];
  then
    removeNXSystemDService "${SYSTEMD_SERVER_SERVICE}"

    return 0
  fi

  #
  # Upstart.
  #

  isUpstartSupported

  if [ ${ret_isUpstartSupported} = 1 ];
  then
    removeNXserverConf

    return 0
  fi

  #
  # Init.
  #

  removeInitServiceScript "nxserver"

  commandRm "/etc/init.d/nxserver" "warn"

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

    if [ -h /etc/rc0.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -r /etc/rc0.d/K99nxserver" \
          "Unable to remove '/etc/rc0.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/rc2.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -r /etc/rc2.d/S99nxserver" \
          "Unable to remove '/etc/rc2.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc3.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -r /etc/rc3.d/S99nxserver" \
          "Unable to remove '/etc/rc3.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc0.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -r /etc/rc0.d/K01nxserver" \
          "Unable to remove '/etc/rc0.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -r /etc/rc6.d/K01nxserver" \
          "Unable to remove '/etc/rc6.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc5.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -r /etc/rc5.d/S99nxserver" \
          "Unable to remove '/etc/rc5.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -r /etc/rc6.d/S99nxserver" \
          "Unable to remove '/etc/rc6.d/S99nxserver'" "warn"
    fi

  elif [ "${system}" = "suse" ];
  then

    if [ -h /etc/init.d/rc3.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc3.d/S99nxserver" \
          "Unable to remove '/etc/init.d/rc3.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/init.d/rc2.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc2.d/S99nxserver" \
          "Unable to remove '/etc/init.d/rc2.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/init.d/rc5.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc5.d/S99nxserver" \
          "Unable to remove '/etc/init.d/rc5.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/init.d/rc6.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc6.d/S99nxserver" \
          "Unable to remove '/etc/init.d/rc6.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/init.d/rc6.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc6.d/K99nxserver" \
          "Unable to remove '/etc/init.d/rc6.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/init.d/rc6.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc6.d/K01nxserver" \
          "Unable to remove '/etc/init.d/rc6.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/init.d/rc0.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc0.d/K99nxserver" \
          "Unable to remove '/etc/init.d/rc0.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/init.d/rc0.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/init.d/rc0.d/K01nxserver" \
          "Unable to remove '/etc/init.d/rc0.d/K01nxserver'" "warn"
    fi

  elif [ "${system}" = "slackware" ];
  then

    if [ -h /etc/rc3.d/S99nxserver ];
    then

      runCommand "${RMCOMMAND} -f /etc/rc3.d/S99nxserver" \
          "Unable to remove '/etc/rc3.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc2.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc2.d/S99nxserver" \
          "Unable to remove '/etc/rc2.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc5.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc5.d/S99nxserver" \
          "Unable to remove '/etc/rc5.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc6.d/S99nxserver" \
          "Unable to remove '/etc/rc6.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc6.d/K99nxserver" \
          "Unable to remove '/etc/rc6.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc6.d/K01nxserver" \
          "Unable to remove '/etc/rc6.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc0.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc0.d/K99nxserver" \
          "Unable to remove '/etc/rc0.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/rc0.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc0.d/K01nxserver" \
          "Unable to remove '/etc/rc0.d/K01nxserver'" "warn"
    fi

  elif [ "${system}" = "debian" ] || [ "x$system" = "xubuntu" ] || \
       [ "x$system" = "xlinuxmint" ] || [ "x$system" = "xelementary" ];
  then

    if [ -h /etc/rc3.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc3.d/S99nxserver" \
          "Unable to remove '/etc/rc3.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc2.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc2.d/S99nxserver" \
          "Unable to remove '/etc/rc2.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc5.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc5.d/S99nxserver" \
          "Unable to remove '/etc/rc5.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc6.d/K99nxserver" \
          "Unable to remove '/etc/rc6.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc6.d/K01nxserver" \
          "Unable to remove '/etc/rc6.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc6.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc6.d/S99nxserver" \
          "Unable to remove '/etc/rc6.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc0.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc0.d/K99nxserver" \
          "Unable to remove '/etc/rc0.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/rc0.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc0.d/K01nxserver" \
          "Unable to remove '/etc/rc0.d/K01nxserver'" "warn"
    fi

    runCommand "${UPDATERCDCOMMAND} nxserver disable" \
        "Unable to run 'update-rc.d nxserver disable'" "log"

    runCommand "${UPDATERCDCOMMAND} nxserver remove" \
        "Unable to run 'update-rc.d nxserver remove'" "warn"

  else
    if [ -h /etc/rc.d/rc3.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc3.d/S99nxserver" \
          "Unable to remove '/etc/rc.d/rc3.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc3.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc3.d/K01nxserver" \
          "Unable to remove '/etc/rc.d/rc3.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc2.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc2.d/S99nxserver" \
          "Unable to remove '/etc/rc.d/rc2.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc2.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc2.d/K01nxserver" \
          "Unable to remove '/etc/rc.d/rc2.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc4.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc4.d/S99nxserver" \
          "Unable to remove '/etc/rc.d/rc4.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc4.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc4.d/K01nxserver" \
          "Unable to remove '/etc/rc.d/rc4.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc5.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc5.d/S99nxserver" \
          "Unable to remove '/etc/rc.d/rc5.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc5.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc5.d/K01nxserver" \
          "Unable to remove '/etc/rc.d/rc5.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc6.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc6.d/S99nxserver" \
          "Unable to remove '/etc/rc.d/rc6.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc6.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc6.d/K99nxserver" \
          "Unable to remove '/etc/rc.d/rc6.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc6.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc6.d/K01nxserver" \
          "Unable to remove '/etc/rc.d/rc6.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc0.d/S99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc0.d/S99nxserver" \
          "Unable to remove '/etc/rc.d/rc0.d/S99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc0.d/K99nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc0.d/K99nxserver" \
          "Unable to remove '/etc/rc.d/rc0.d/K99nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc0.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc0.d/K01nxserver" \
          "Unable to remove '/etc/rc.d/rc0.d/K01nxserver'" "warn"
    fi

    if [ -h /etc/rc.d/rc1.d/K01nxserver ];
    then
      runCommand "${RMCOMMAND} -f /etc/rc.d/rc1.d/K01nxserver" \
          "Unable to remove '/etc/rc.d/rc1.d/K01nxserver'" "warn"
    fi
  fi
}

addNXinit ()
{
  #
  # MacOS.
  #

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

    return 0
  fi

  #
  # Linux.
  #  SystemD.
  #

  isSystemDSupported

  if [ ${ret_isSystemDSupported} = 1 ];
  then
    if [ "${1}x" = "autox" ];
    then
      replaceNXSystemDService
    fi
  fi

  removeNXinit

  if [ ${ret_isSystemDSupported} = 1 ];
  then
    addNXSystemDService "${SYSTEMD_SERVER_SERVICE}"
    ${SYSTEMCTLCOMMAND} daemon-reload

    return 0
  fi

  #
  # Upstart.
  #

  isUpstartSupported

  if [ ${ret_isUpstartSupported} = 1 ];
  then
    addNXserverConf

    return 0
  fi

  if [ "${system}" = "suse" ];
  then
    ${SEDCOMMAND} -e 's/# Default-Start:.*/# Default-Start:  2 3 5/' -e 's/# Default-Stop:.*/# Default-Stop:  0 1 4 6/' \
        "${NX_ROOT}/scripts/init/nxserver" > "${NX_ROOT}/scripts/init/nxserver.tmp"

    commandRestoreFile "${NX_ROOT}/scripts/init/nxserver" "tmp"
  fi

  if [ "${system}" = "slackware" ];
  then
    ${SEDCOMMAND} -e 's/# Default-Start:.*/# Default-Start:  2 3 5/' -e 's/# Default-Stop:.*/# Default-Stop:  0 1 4 6/' \
        "${NX_ROOT}/scripts/init/nxserver" > "${NX_ROOT}/scripts/init/nxserver.tmp"

    commandRestoreFile "${NX_ROOT}/scripts/init/nxserver" "tmp"
  fi

  if [ "${system}" = "debian" ] || [ "x$system" = "xubuntu" ] || \
     [ "x$system" = "xlinuxmint" ] || [ "x$system" = "xelementary" ];
  then
    ${SEDCOMMAND} -e 's/# Default-Start:.*/# Default-Start:  2 3 4 5/' -e 's/# Default-Stop:.*/# Default-Stop:   0 1 6/' \
        "${NX_ROOT}/scripts/init/nxserver" > "${NX_ROOT}/scripts/init/nxserver.tmp"

    commandRestoreFile "${NX_ROOT}/scripts/init/nxserver" "tmp"
  fi

  ${SEDCOMMAND} -e 's:NX_ROOT:'${NX_ROOT}':g' "${NX_ROOT}/scripts/init/nxserver" > "${NX_ROOT}/scripts/init/nxserver.tmp"
  commandRestoreFile "${NX_ROOT}/scripts/init/nxserver" "tmp"

  runCommand "${CATCOMMAND} '${NX_ROOT}/scripts/init/nxserver' > /etc/init.d/nxserver"\
      "Unable to create: /etc/init.d/nxserver" "warn"

  runCommand "${CHMODCOMMAND} +x /etc/init.d/nxserver" \
      "Cannot set permissions of /etc/init.d/nxserver file" "warn"

  if [ -x ${INSSERVCOMMAND} ];
  then
    enableInitServiceScript "nxserver"

    setSELinuxContext "unconfined_exec_t" "/etc/init.d/nxserver"

    if [ ${ret_enableInitServiceScript} = 0 ];
    then
      return 0
    fi
  else
    setSELinuxContext "unconfined_exec_t" "/etc/init.d/nxserver"
  fi

  temppdir=$(${PWDCOMMAND})

  if [ "${system}" = "solaris" ];
  then
    if [ -d /etc/rc0.d ];
    then
      cd /etc/rc0.d

      if [ ! -h /etc/rc0.d/K01nxserver ];
      then
        runCommand "${LNCOMMAND} -sf ../init.d/nxserver K01nxserver" \
            "Unable to create link: '/etc/rc0.d/K01nxserver'" "warn"

      fi
    fi

    if [ -d /etc/rc3.d ];
    then
      cd /etc/rc3.d

      if [ ! -h /etc/rc3.d/S99nxserver ];
      then
        runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
            "Unable to create link: '/etc/rc3.d/S99nxserver'" "warn"
      fi
    fi

    if [ -d /etc/rc2.d ];
    then
      cd /etc/rc2.d

      if [ ! -h /etc/rc2.d/S99nxserver ];
      then
        runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
            "Unable to create link: '/etc/rc2.d/S99nxserver'" "warn"
      fi
    fi

    if [ -d /etc/rc5.d ];
    then
      cd /etc/rc5.d

      if [ ! -h /etc/rc5.d/S99nxserver ];
      then
        runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
            "Unable to create link: '/etc/rc5.d/S99nxserver'" "warn"
      fi
    fi

    if [ -d /etc/rc6.d ];
    then
      cd /etc/rc6.d

      if [ ! -h /etc/rc6.d/K01nxserver ];
      then
        runCommand "${LNCOMMAND} -sf ../init.d/nxserver K01nxserver" \
            "Unable to create link: '/etc/rc6.d/K01nxserver'" "warn"
      fi
    fi

  elif [ "${system}" = "suse" ];
  then
    cd /etc/init.d/rc3.d
    runCommand "${LNCOMMAND} -sf ../nxserver S99nxserver" \
        "Unable to create link: '/etc/init.d/rc3.d/S99nxserver'" "warn"

    cd /etc/init.d/rc2.d
    runCommand "${LNCOMMAND} -sf ../nxserver S99nxserver" \
        "Unable to create link: '/etc/init.d/rc2.d/S99nxserver'" "warn"

    cd /etc/init.d/rc5.d
    runCommand "${LNCOMMAND} -sf ../nxserver S99nxserver" \
        "Unable to create link: '/etc/init.d/rc5.d/S99nxserver'" "warn"

    cd /etc/init.d/rc6.d
    runCommand "${LNCOMMAND} -sf ../nxserver K01nxserver" \
        "Unable to create link: '/etc/init.d/rc6.d/K01nxserver'" "warn"

    cd /etc/init.d/rc0.d
    runCommand "${LNCOMMAND} -sf ../nxserver K01nxserver" \
        "Unable to create link: '/etc/init.d/rc0.d/K01nxserver'" "warn"

  elif [ "${system}" = "slackware" ];
  then
    cd /etc/rc3.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/init.d/rc3.d/S99nxserver'" "warn"

    cd /etc/rc2.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/init.d/rc2.d/S99nxserver'" "warn"

    cd /etc/rc5.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/init.d/rc5.d/S99nxserver'" "warn"

    cd /etc/rc6.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver K01nxserver" \
        "Unable to create link: '/etc/init.d/rc6.d/K01nxserver'" "warn"

    cd /etc/rc0.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver K01nxserver" \
        "Unable to create link: '/etc/init.d/rc0.d/K01nxserver'" "warn"

  elif [ "${system}" = "debian" ] || [ "x$system" = "xubuntu" ] || \
       [ "x$system" = "xlinuxmint" ] || [ "x$system" = "xelementary" ];
  then
    cd /etc/rc3.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/rc3.d/S99nxserver'" "warn"

    cd /etc/rc2.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/rc2.d/S99nxserver'" "warn"

    cd /etc/rc4.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/rc4.d/S99nxserver'" "warn"

    cd /etc/rc5.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/rc5.d/S99nxserver'" "warn"

    cd /etc/rc6.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver K01nxserver" \
        "Unable to create link: '/etc/rc6.d/K01nxserver'" "warn"

    cd /etc/rc0.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver K01nxserver" \
        "Unable to create link: '/etc/rc0.d/K01nxserver'" "warn"

    cd /etc/rc1.d
    runCommand "${LNCOMMAND} -sf ../init.d/nxserver K01nxserver" \
        "Unable to create link: '/etc/rc1.d/K01nxserver'" "warn"

    runCommand "${UPDATERCDCOMMAND} nxserver defaults" \
        "Unable to run 'update-rc.d nxserver defaults'" "warn"

  else

    cd /etc/rc.d/rc3.d
    runCommand "${LNCOMMAND} -sf /etc/init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/rc.d/rc3.d/S99nxserver'" "warn"

    cd /etc/rc.d/rc2.d
    runCommand "${LNCOMMAND} -sf /etc/init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/rc.d/rc2.d/S99nxserver'" "warn"

    cd ../rc5.d
    runCommand "${LNCOMMAND} -sf /etc/init.d/nxserver S99nxserver" \
        "Unable to create link: '/etc/rc.d/rc5.d/S99nxserver'" "warn"

    cd ../rc6.d
    runCommand "${LNCOMMAND} -sf /etc/init.d/nxserver K01nxserver" \
        "Unable to create link: '/etc/rc.d/rc6.d/K01nxserver'" "warn"

    cd ../rc0.d
    runCommand "${LNCOMMAND} -sf /etc/init.d/nxserver K01nxserver" \
        "Unable to create link: '/etc/rc.d/rc0.d/K01nxserver'" "warn"
  fi

  cd "$temppdir"
}

checkNXSystemDService ()
{
  systemdFile="$1"
  ret_checkNXSystemDService="0"

  enabledOut=$(${SYSTEMCTLCOMMAND} is-enabled ${systemdFile} 2>/dev/null)

  if [ "x$enabledOut" = "xenabled" ];
  then
    ret_checkNXSystemDService="1"
  fi

  return 0
}

runUpstartServer ()
{
  runCommand "$STARTCOMMAND $UPSTART_SERVER_SERVICE" "cmd"
}

disableUpstartServer ()
{
  runCommand "$STOPCOMMAND $UPSTART_SERVER_SERVICE" "cmd"
}

checkUpstartServer ()
{
  modeStatus=$($STATUSCOMMAND $UPSTART_SERVER_SERVICE)

  if [ "$modeStatus" = "$UPSTART_SERVER_SERVICE stop/waiting" ];
  then
    ret_checkNXUpstart=0
  else
    ret_checkNXUpstart=1
  fi
  ret_checkNXinit=$ret_checkNXUpstart
}

checkNXinit ()
{
  ret_checkNXinit=0

  if [ "${system}" = "macosx" ];
  then
    if [ -f "/Library/LaunchDaemons/com.nomachine.server.plist" ];
    then
      ret_checkNXinit=1
    fi

    return 0
  fi

  isSystemDSupported

  if [ ${ret_isSystemDSupported} = 1 ];
  then
    checkNXSystemDService "${SYSTEMD_SERVER_SERVICE}"
    ret_checkNXinit="${ret_checkNXSystemDService}"

    return 0
  else
    isUpstartSupported

    if [ ${ret_isUpstartSupported} = 1 ];
    then
      checkUpstartServer
    fi
  fi

  if [ -f /etc/init.d/nxserver ];
  then
    ret_checkNXinit=1
  fi

  return 0
}

genNXUsersDSAKeys ()
{
  #
  # Generating DSA keys pair.
  # This command is executed only in installation procedure.
  # Upgrade of NoMachine 3.5 is treated like installation.
  #

  if [ -f "${NX_ROOT}/etc/keys/node.localhost.id_dsa" ];
  then
    printMsg "Found file: ${NX_ROOT}/etc/keys/node.localhost.id_dsa" "cmd"
    printMsg "Skipping adding DSA key for user ${USER_NX}" "cmd"

  else

    printMsg "Adding DSA key for user ${USER_NX}" "cmd"

    commandRmIfExist "${NX_ROOT}/etc/keys/node.localhost.id_dsa" "cmd"
    commandRmIfExist "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" "cmd"

    runShCommand "NX_SYSTEM="${NX_ROOT}" LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH'\
                     ${NXKEYGENCOMMAND} -k '${NX_ROOT}/etc/keys/node.localhost.id_dsa' -p\
                         '${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub' -t dsa"\
                             "Skipping adding DSA key for user ${USER_NX}" "cmd"

  fi
}

genNXUsersRSAKeys ()
{
  #
  # Generating RSA keys pair.
  # This command is executed only in update procedure and
  # also in NoMachine 3.5 upgrade which is treated like installation.
  #

  if [ -f "${NX_ROOT}/etc/keys/node.localhost.id_rsa" ];
  then
    printMsg "Found file: ${NX_ROOT}/etc/keys/node.localhost.id_rsa" "cmd"
    printMsg "Skipping adding RSA key for user ${USER_NX}" "cmd"

  else

    printMsg "Adding RSA key for user ${USER_NX}" "cmd"

    commandRmIfExist "${NX_ROOT}/etc/keys/node.localhost.id_rsa" "cmd"
    commandRmIfExist "${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" "cmd"

    runShCommand "NX_SYSTEM="${NX_ROOT}" LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH'\
                     ${NXKEYGENCOMMAND} -k '${NX_ROOT}/etc/keys/node.localhost.id_rsa' -p\
                         '${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub' -t rsa"\
                             "Skipping adding RSA key for user ${USER_NX}" "cmd"

  fi
}

genNXUsersKeys ()
{
  #
  # Executing only in installation procedure.
  # Upgrade from NoMachine 3.5 is treated as installation.
  #

  if [ ! -d "${NX_ROOT}/etc/keys" ];
  then
    commandMkDir "${NX_ROOT}/etc/keys" "warn"
  fi

  if [ -f "${NX_ROOT}/etc/users.id_dsa" ];
  then
    printMsg "Found file: ${NX_ROOT}/etc/users.id_dsa" "cmd"
    printMsg "Not adding SSH key for user nx" "cmd"

    commandMv "${NX_ROOT}/etc/users.id_dsa" "${NX_ROOT}/etc/keys/node.localhost.id_dsa" "warn"
    commandMv "${NX_ROOT}/etc/users.id_dsa.pub" "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" "warn"

    genNXUsersRSAKeys

  elif [ "x${NX_MPKG_PACKAGE}" = "xnode" ];
  then

    #
    # Do not generate new pair of keys for
    # NoMachine Terminal Server Node 4 when
    # upgrade from NoMachine Advanced Server Node 3.
    #

    if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" ];
    then
      printMsg "File not found: ${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" "cmd"
      printMsg "Adding DSA key for user ${USER_NX}" "cmd"

      genNXUsersDSAKeys
    fi

    if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" ];
    then
      printMsg "File not found: ${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" "cmd"
      printMsg "Adding RSA key for user ${USER_NX}" "cmd"

      genNXUsersRSAKeys
    fi
  else

    if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_dsa" ];
    then
      printMsg "File not found: ${NX_ROOT}/etc/keys/node.localhost.id_dsa" "cmd"
      printMsg "Adding DSA key for user ${USER_NX}" "cmd"

      genNXUsersDSAKeys
    fi

    if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_rsa" ];
    then
      printMsg "File not found: ${NX_ROOT}/etc/keys/node.localhost.id_rsa" "cmd"
      printMsg "Adding RSA key for user ${USER_NX}" "cmd"

      genNXUsersRSAKeys
    fi
  fi
}

setUserShell ()
{
  username=$1
  usershell=""
  ret_setUserShell=0

  if [ "x${username}" = "x" ];
  then
    printMsg "Retrieving shell: User not specified" "warn"
    ret_setUserShell=1
    return 0
  fi

  ${IDCOMMAND} ${username} > /dev/null 2>&1

  if [ $? = 0 ];
  then

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

    usershell=$(${CATCOMMAND} /etc/passwd | ${CUTCOMMAND} -f1,7 -d: | ${GREPCOMMAND} "^${username}:" | ${CUTCOMMAND} -f2 -d:)

    if [ "x${usershell}" = "x" ];
    then
      printMsg "Cannot find user "${username}" at /etc/passwd file." "warn"
      ret_setUserShell=3

      return 0

    elif [ "${usershell}" != "${NXSHELL}" ];
    then
      ${USERMODCOMMAND} -s "${NXSHELL}" ${username}
    fi
  else
    printMsg "User "${username}" doesn't exist" "warn"
    ret_setUserShell=2

    return 0
  fi

  return 0
}


archiveNXUsersKeys ()
{
  if [ "${system}" != "solaris" ];
  then
    if [ -f "${NX_ROOT}/etc/users.id_dsa" ];
    then
      printMsg "Saving private key to: ${NX_ROOT}/etc/keys/node.localhost.id_dsa.backup" "warn"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/users.id_dsa' '${NX_ROOT}/etc/keys/node.localhost.id_dsa.backup'"\
                     "Cannot move private key ${NX_ROOT}/etc/users.id_dsa to ${NX_ROOT}/etc/keys/node.localhost.id_dsa.backup" "error"

      printMsg "Saving public key to: ${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub.backup" "warn"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/users.id_dsa.pub' '${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub.backup'"\
                     "Cannot move public key ${NX_ROOT}/etc/users.id_dsa.pub to ${NX_ROOT}/etc/keys/node.localhost.id_dsa.backup" "error"
    fi

    if [ -f "${NX_ROOT}/etc/keys/node.locahost.id_dsa" ];
    then
      printMsg "Saving private key to: ${NX_ROOT}/etc/keys/node.localhost.id_dsa.backup"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/keys/node.localhost.id_dsa' '${NX_ROOT}/etc/keys/node.localhost.id_dsa.backup'"\
                     "Cannot move private key ${NX_ROOT}/etc/keys/node.localhost.id_dsa to ${NX_ROOT}/etc/keys/node.localhost.id_dsa.backup" "error"

      printMsg "Saving public key to: ${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub.backup"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub' '${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub.backup'"\
                     "Cannot move public key ${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub to ${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub.backup" "error"
    fi

    #
    # Backuping new RSA keys
    #

    if [ -f "${NX_ROOT}/etc/users.id_rsa" ];
    then
      printMsg "Saving private key to: ${NX_ROOT}/etc/keys/node.localhost.id_rsa.backup" "warn"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/users.id_rsa' '${NX_ROOT}/etc/keys/node.localhost.id_rsa.backup'"\
                     "Cannot move private key ${NX_ROOT}/etc/users.id_rsa to ${NX_ROOT}/etc/keys/node.localhost.id_rsa.backup" "error"

      printMsg "Saving public key to: ${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub.backup" "warn"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/users.id_rsa.pub' '${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub.backup'"\
                     "Cannot move public key ${NX_ROOT}/etc/users.id_rsa.pub to ${NX_ROOT}/etc/keys/node.localhost.id_rsa.backup" "error"
    fi

    if [ -f "${NX_ROOT}/etc/keys/node.locahost.id_rsa" ];
    then
      printMsg "Saving private key to: ${NX_ROOT}/etc/keys/node.localhost.id_rsa.backup"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/keys/node.localhost.id_rsa' '${NX_ROOT}/etc/keys/node.localhost.id_rsa.backup'"\
                     "Cannot move private key ${NX_ROOT}/etc/keys/node.localhost.id_rsa to ${NX_ROOT}/etc/keys/node.localhost.id_rsa.backup" "error"

      printMsg "Saving public key to: ${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub.backup"
      runCommand "${MVCOMMAND} '${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub' '${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub.backup'"\
                     "Cannot move public key ${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub to ${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub.backup" "error"
    fi
  fi
}

makeNXConfigServerPersonal ()
{
  #
  # NXSTOPSERVERFLAG
  #

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

setPermForLicenseFile ()
{
  if [ -f "${LICENSE_FILE}" ];
  then
    commandChownChmod "${USER_NX}:${ROOTGNAME}" "0400" "${LICENSE_FILE}" "error"
  fi
}

setSELinuxContextForLogs ()
{
  if [ ${SELINUX_ENABLED} = 1 ];
  then
    if [ -d "${NX_VAR_DIR}/log" ];
    then
      setSELinuxContextR "var_log_t" "${NX_VAR_DIR}/log"
    fi

    if [ -d "/etc/NX" ];
    then
      restoreContextForDir "/etc/NX"
    fi

    if [ -f "${NX_VAR_DIR}/log/server.log" ];
    then
      setSELinuxContextR "var_log_t" "${NX_VAR_DIR}/log/server.log"
    fi
  fi
}

installDbfile ()
{
  #
  # Restoring or creating new DB file.
  #

  dbFile="${1}"

  if [ -f "${dbFile}" ];
  then
    printMsg "Found file: ${dbFile}" "cmd"
    printMsg "Skipping overwriting with: ${dbFile}.sample" "cmd"
  elif [ -f "${NX_ROOT}/etc/${dbFile}.backup" ];
  then
    printMsg "Found file: ${dbFile}.backup" "cmd"
    printMsg "Restoring: ${dbFile} from: ${dbFile}.backup" "cmd"

    commandRestoreFile "${dbFile}" "backup"
  else
    printMsg "Copying: ${dbFile} from: ${dbFile}.sample" "cmd"

    commandCp "${dbFile}.sample" "${dbFile}" "error"
  fi
}

lockDbFile ()
{
  #
  # Creating lock file for DB file and setting owner.
  #

  dbFile="${1}"

  if [ ! -f "${dbFile}.lock" ];
  then
    commandTouch "${dbFile}.lock" "error"
  fi

  commandChown "${USER_NX}:${ROOTGNAME}" "${dbFile}.lock" "error"
}

makeNXConfigServer ()
{
  #
  # NXSTOPSERVERFLAG
  #

  if [ ! -f "${NXSTOPSERVERFLAG}" ];
  then
    commandTouch "${NXSTOPSERVERFLAG}" "error"
    commandChown "${USER_NX}:${ROOTGNAME}" "${NXSTOPSERVERFLAG}" "error"
  fi

  setPermForLicenseFile
}

updateNXConfigServer ()
{
  makeNXConfigServer

  if [ ! -f "${NXSTOPSERVERFLAG}" ];
  then
    commandTouch "${NXSTOPSERVERFLAG}" "error"
    commandChown "${USER_NX}:${ROOTGNAME}" "${NXSTOPSERVERFLAG}" "error"
  fi

  setPermForLicenseFile
}

setPermissionsAndLock ()
{
  #
  # Setting proper permisions and creating lock file.
  # 1 - file to install and lock.
  #

  file="${1}"

  commandChownChmod "${USER_NX}:${ROOTGNAME}" "0600" "${file}" "error"

  lockDbFile "${file}"
}

checkNXConfiguration ()
{
  commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc"      "error"
  commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys" "error"

  commandChown "${USER_NX}:${NX_GROUP}" "${NX_ROOT}/etc/server.cfg" "error"

  if [ "x${NX_POSTINST}" != "x1" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys/node.localhost.id_dsa" "error"
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys/node.localhost.id_rsa" "error"
  fi

  commandChown "${USER_NX}:${ROOTGNAME}" "${NX_VAR_DIR}/" "error"
  commandChown "${USER_NX}:${ROOTGNAME}" "${NX_VAR_DIR}/db" "error"

  commandChownR "${USER_NX}:${ROOTGNAME}" "${NX_VAR_DIR}/db/node" "error"
  commandChmod  "0755" "${NX_VAR_DIR}/db/node" "error"

  commandMkDir  "${NX_VAR_DIR}/db/server" "error"
  commandChownR "${USER_NX}:${ROOTGNAME}" "${NX_VAR_DIR}/db/server" "error"
  commandChmod  "1755" "${NX_VAR_DIR}/db/server" "warn"

  commandChown "${USER_NX}:${ROOTGNAME}" "${NX_VAR_DIR}/run" "error"
  commandChmod "1755" "${NX_VAR_DIR}/run" "warn"
  commandChownIfExist "${USER_NX}:${USER_NX}" "${NX_VAR_DIR}/run/server.pid" "warn"

  if [ "${system}" = "macosx" ];
  then
    commandChmod "777" "${NX_VAR_DIR}/log" "warn"
  fi

  if [ -f "${NX_VAR_DIR}/num" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_VAR_DIR}/num" "warn"
  fi

  if [ -f "${NX_VAR_DIR}/run/localsession.pid" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_VAR_DIR}/run/localsession.pid" "error"
  fi

  if [ -f "${NX_ROOT}/etc/keys/host/nx_host_rsa_key" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys/host/nx_host_rsa_key" "error"
  fi

  if [ -f "${NX_ROOT}/etc/keys/host/nx_host_rsa_key.crt" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys/host/nx_host_rsa_key.crt" "error"
  fi

  if [ -f "${NX_ROOT}/etc/server.cfg.backup" ];
  then
    commandChown "${USER_NX}:${NX_GROUP}" "${NX_ROOT}/etc/server.cfg.backup" "warn"
  fi

  if [ -f "${NX_ROOT}/etc/node.cfg.backup" ];
  then
    commandChown "${USER_NX}:${NX_GROUP}" "${NX_ROOT}/etc/node.cfg.backup" "warn"
  fi

  #
  # broadcast
  #

  if [ ! -f "${NX_VAR_DIR}/broadcast" ];
  then
    runCommand "${TOUCHCOMMAND} '${NX_VAR_DIR}/db/broadcast'" "Cannot initialize broadcast" "warn"
  fi
  commandChown "${USER_NX}" "${NX_VAR_DIR}/db/broadcast" "warn"

  setPermForLicenseFile

  #
  # node.localhost.id_dsa
  #

  if [ -f "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" "error"
  fi

  if [ -f "${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" "error"
  fi

  if [ -f "${NX_ROOT}/etc/uuid" ];
  then
    commandChown "${USER_NX}:${ROOTGNAME}" "${NX_ROOT}/etc/uuid"
  fi
}

checkNXkeys ()
{
  if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_dsa" ];
  then
    printMsgNoDot "Installation of NoMachine server is corrupted: " "error"
    printMsgNoDot "Missing ${NX_ROOT}/etc/keys/node.localhost.id_dsa ssh key file!" "error"
    printMsg "Please uninstall and install the package again" "error"
    printMsg "Bye"

    ${ECHOCOMMAND} ""

    exit 1
  fi

  if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" ];
  then
    printMsgNoDot "Installation of NoMachine server is corrupted:" "error"
    printMsgNoDot "'Missing ${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub ssh key file!" "error"
    printMsg "Please uninstall and install the package again" "error"
    printMsg "Bye"

    ${ECHOCOMMAND} ""

    exit 1
  fi

  if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_rsa" ];
  then
    printMsgNoDot "Installation of NoMachine server is corrupted:" "error"
    printMsgNoDot "Missing ${NX_ROOT}/etc/keys/node.localhost.id_rsa ssh key file!" "error"
    printMsg "Please uninstall and install the package again" "error"
    printMsg "Bye"

    ${ECHOCOMMAND} ""

    exit 1
  fi

  if [ ! -f "${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" ];
  then
    printMsgNoDot "Installation of NoMachine server is corrupted:" "error"
    printMsgNoDot "'Missing ${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub ssh key file!" "error"
    printMsg "Please uninstall and install the package again" "error"
    printMsg "Bye"

    ${ECHOCOMMAND} ""

    exit 1
  fi
}

makeConfBackup ()
{
  if [ -f "${CONFIG_FILE}" ];
  then
    printMsg "Saving configuration file to: ${CONFIG_FILE}.backup" "cmd"
    commandBackupFile "${CONFIG_FILE}" "backup" "error"
  fi
}

resetNXConfigServer ()
{
  resetNXConfig

  if [ -f "${NX_VAR_DIR}/db/broadcast" ];
  then
    cleanNXDb
  fi

  if [ "x${NX_PERSONAL}" = "x1" ];
  then
    return
  fi

  commandChownR "root:${ROOTGNAME}" "${NX_ROOT}/etc" "warn"

  if [ -f "${NXHOME}/.ssh/authorized_keys2" ];
  then
    command="${RMCOMMAND} -f '${NXHOME}/.ssh/authorized_keys2'"
    printMsg "Command: ${command}" "cmd"
    outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

    if [ "$?" != 0 ];
    then
      printMsg "${outCommand}" "warn"
      printMsg "Cannot delete file: ${NXHOME}/.ssh/authorized_keys2" "warn"
      printMsg "User: ${USER_NX} will be able login using its own public key" "warn"
    else
      printMsg "${outCommand}" "cmd"
      printMsg "Result: OK" "cmd"
    fi
  fi

  if [ -f "${NXHOME}/.ssh/authorized_keys" ];
  then
    command="${RMCOMMAND} -f '${NXHOME}/.ssh/authorized_keys'"
    printMsg "Command: ${command}" "cmd"
    outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

    if [ "$?" != 0 ];
    then
      printMsg "${outCommand}" "warn"
      printMsg "Cannot delete file: ${NXHOME}/.ssh/authorized_keys" "warn"
      printMsg "User: ${USER_NX} will be able login using its own public key" "warn"
    else
      printMsg "${outCommand}" "cmd"
      printMsg "Result: OK" "cmd"
    fi
  fi

  commandRm "${NXHOME}/.ssh/known_hosts" "warn"
}

removeEnableLoadBalancingOptionFromCfg ()
{
  ret_removeEnableLoadBalancingOptionFromCfg=0

  CFG_OPTION="EnableLoadBalancing"

  getValueFromCfgFile "${CFG_OPTION}" "${CONFIG_FILE}"

  if [ ${ret_getValueFromCfgFile} = 1 ] || [ ${ret_getValueFromCfgFile} = 2 ];
  then
    removeOptionFromCfg "${CFG_OPTION}" "Enable *or *disable *load *balancing"

    if [ ${ret_getValueFromCfgFile} = 2 ];
    then

      if [ ${cfg_val} = 1 ];
      then
        rule_value="yes"
      else
        rule_value="no"
      fi

      command="'${NXSHELL}' --ruleadd --feature=enable-multinode --value=$rule_value --system"
      rule_out=$("${command}" 2>/dev/null)
      grep_out=$(${ECHOCOMMAND} ${rule_out} | ${GREPCOMMAND} "ERROR" 2>/dev/null)

      if [ "x${grep_out}" != "x" ];
      then
        printMsg "Error while adding the 'enable-multinode' rule" "cmd"

      else
        printMsg "Added 'enable-multinode' rule" "cmd"
      fi
    fi

    ret_removeEnableLoadBalancingOptionFromCfg=1

    return 0
  else
    printMsg "Cannot find key: ${CFG_OPTION} in the config file" "cmd"
    ret_removeEnableLoadBalancingOptionFromCfg=${ret_getValueFromCfgFile}

    return 0
  fi
}

removeEnableGuestUserOptionFromCfg ()
{
  ret_removeEnableGuestUserOptionFromCfg=0

  CFG_OPTION="EnableGuestUser"

  getValueFromCfgFile "${CFG_OPTION}" "${CONFIG_FILE}"
  if [ ${ret_getValueFromCfgFile} = 1 ] || [ ${ret_getValueFromCfgFile} = 2 ];
  then
    removeOptionFromCfg "${CFG_OPTION}" "Enable *or *disable *support *for *automatic *provision"

    if [ ${ret_getValueFromCfgFile} = 2 ];
    then
      if [ ${cfg_val} = 1 ];
      then
        rule_value="yes"
      else
        rule_value="no"
      fi

      command="'${NXSHELL}' --ruleadd --feature=enable-guest --value=$rule_value --system"
      rule_out=$("${command}" 2>/dev/null)
      grep_out=$(${ECHOCOMMAND} "${rule_out}" | ${GREPCOMMAND} "ERROR" 2>/dev/null)

      if [ "x${grep_out}" != "x" ];
      then
        printMsg "Error while adding 'enable-guest' rule" "cmd"
      else
        printMsg "Added 'enable-guest' rule" "cmd"
      fi
    fi

    ret_removeEnableGuestUserOptionFromCfg=1
    return 0
  else
    printMsg "Cannot find key: ${CFG_OPTION} in the config file" "cmd"

    ret_removeEnableGuestUserOptionFromCfg=${ret_getValueFromCfgFile}
  fi
}

removeEnableUserProfileFromCfg ()
{
  removeEnableUserProfileFromCfg=0
  CFG_OPTION="EnableUserProfile"

  getValueFromCfgFile "${CFG_OPTION}" "${CONFIG_FILE}"

  if [ ${ret_getValueFromCfgFile} = 1 ] || [ ${ret_getValueFromCfgFile} = 2 ];
  then
    removeOptionFromCfg "${CFG_OPTION}" "Enable *or *disable *support *for *user *profiles"

    if [ ${ret_getValueFromCfgFile} = 2 ];
    then
      if [ ${cfg_val} = 1 ];
      then
        rule_value="yes"
      else
        rule_value="no"
      fi

      command="'${NXSHELL}' --ruleadd --feature=enable-profiles --value=$rule_value --system"
      rule_out=$("${command}" 2>/dev/null)
      grep_out=$(${ECHOCOMMAND} "${rule_out}" | ${GREPCOMMAND} "ERROR" 2>/dev/null)

      if [ "x${grep_out}" != "x" ];
      then
        printMsg "Error while adding 'enable-profiles' rule" "cmd"

      else
        printMsg "Added 'enable-profiles' rule" "cmd"
      fi
    fi
    ret_removeEnableUserProfileFromCfg=1

    return 0
  else
    printMsg "Cannot find key: ${CFG_OPTION} in the config file" "cmd"
    ret_removeEnableUserProfileFromCfg=${ret_getValueFromCfgFile}
  fi
}

removeOldOptionsFromCfg3 ()
{
  removeEnableLoadBalancingOptionFromCfg
  removeEnableGuestUserOptionFromCfg
  removeEnableUserProfileFromCfg

  removeOptionFromCfg "EnableFullDesktopSharing" "Allow *the *NX *user *to *connect *to *a *desktop *owned *by *a *user *who *is"
  removeOptionFromCfg "EnableAdministratorDesktopSharing" "Allow *the *NX *user *to *connect *to *a *desktop *owned *by *root"
  removeOptionFromCfg "EnableSystemDesktopSharingAuthorization" "Enable *or *disable *NX *Server *requiring *authorization *before *sharing"
  removeOptionFromCfg "EnableUnencryptedSession" "Enable *or *disable *SS. *encryption *of *all *traffic"
  removeOptionFromCfg "EnableStatistics" "Enable *or *disable *statistics"
  removeOptionFromCfg "ServerSensorPort" "Specify.*port *where.*server.*contact.*nxsensor *daemons"
  removeOptionFromCfg "EnableNodeMonitoring" "Enable *or *disable *monitoring.*ode"
  removeOptionFromCfg "NodeResponseTimeout" "Set *for *how *long.*erver *daemon *has.*wait.*reply"
}

removeServerSensorHostOptionFromCfg ()
{
  removeServerSensorHostOptionFromCfg=0

  CFG_OPTION="ServerSensorHost"
  getValueFromCfgFile "${CFG_OPTION}" "${CONFIG_FILE}"
  if [ ${ret_getValueFromCfgFile} = 1 ] || [ ${ret_getValueFromCfgFile} = 2 ];
  then
    ${SEDCOMMAND} -e '/Specify *the *hostname *or *IP *address *where *the *nxsensor *daemon *will/,/'"${CFG_OPTION}"'/d' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    ${SEDCOMMAND} -e '/^#$/{ N; /^#\n$/d}' "${CONFIG_FILE}.tmp" > "${CONFIG_FILE}"
    ${SEDCOMMAND} -e '/.*'"${CFG_OPTION}"'.*=.*/d' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

    commandRestoreFile "${CONFIG_FILE}" "tmp"
    printMsgRemoveKeyFromConfigFile "${CFG_OPTION}"

    return
  else
    removeServerSensorHostOptionFromCfg=${ret_getValueFromCfgFile}
  fi
}

removeOldOptionsFromCfg ()
{
  removeServerSensorHostOptionFromCfg
  removeOldOptionsFromCfg3
}

updateSuspendKeysDescription ()
{
  ${SEDCOMMAND} 's/oldest *suspended *sessions/oldest disconnected sessions/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${SEDCOMMAND} 's/automatic *kill *of *the *suspended/automatic kill of the disconnected/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${SEDCOMMAND} 's/Suspended *sessions/Disconnected sessions/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${SEDCOMMAND} 's/suspend *sessions/disconnect sessions/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${SEDCOMMAND} 's/terminate *oldest *suspended *sessions:/terminate oldest disconnected sessions:/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${SEDCOMMAND} 's/terminate *any *suspended *session/terminate any disconnected session/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"

  ${SEDCOMMAND} 's/the *session *is *suspended./the session is disconnected./g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
  commandRestoreFile "${CONFIG_FILE}" "tmp"
}

fixoldkeyfile ()
{
  #
  # This is executed only in update procedure
  #

  if [ -f "${NXHOME}/.ssh/client.id_dsa.key" ];
  then
    commandRm "${NXHOME}/.ssh/client.id_dsa.key" "warn"
  fi

  if [ -f "${NX_ROOT}/etc/users.id_dsa" ];
  then
    printMsg "Found file: ${NX_ROOT}/etc/users.id_dsa" "cmd"
    printMsg "Skipping adding DSA key for user ${USER_NX}" "cmd"

    commandMv "${NX_ROOT}/etc/users.id_dsa" "${NX_ROOT}/etc/keys/node.localhost.id_dsa" "error"
  fi

  if [ -f "${NX_ROOT}/etc/users.id_dsa.pub" ];
  then
    commandMv "${NX_ROOT}/etc/users.id_dsa.pub" "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" "error"
  fi

  if [ -f "${NX_ROOT}/etc/users.id_rsa" ];
  then
    printMsg "Found file: ${NX_ROOT}/etc/users.id_rsa" "cmd"
    printMsg "Skipping adding RSA key for user ${USER_NX}" "cmd"

    commandMv "${NX_ROOT}/etc/users.id_rsa" "${NX_ROOT}/etc/keys/node.localhost.id_rsa" "error"
  fi

  if [ -f "${NX_ROOT}/etc/users.id_rsa.pub" ];
  then
    commandMv "${NX_ROOT}/etc/users.id_rsa.pub" "${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" "error"
  fi
}

isFreePackage ()
{
  ret_isFreePackage=1

  if [ ! -f "${NX_ROOT}/etc/server.lic" ]; then
    ret_isFreePackage=0

    return 0
  fi

  if [ "x${LICENSE_ACRONYM}" = "x" ];
  then
    getLicenseAcronym

    if [ "x${LICENSE_ACRONYM}" = "x" ];
    then
      printMsg "Cannot read license acronym" "warn"

      return 0
    fi
  fi

  #
  # Version 4.X.
  #

  if [ ${LICENSE_ACRONYM:1} = S ];
  then
    return 0
  fi

  #
  # Version 3.X.
  #

  if [ ${LICENSE_ACRONYM:1} = FE ];
  then
    return 0
  fi

  ret_isFreePackage=0
}

setConnectionMethods ()
{
  isFreePackage

  if [ $ret_isFreePackage = 1 ];
  then
    setValueAtCfgFile "${CONFIG_FILE}" "ClientConnectionMethods" "NX"

    return 0
  fi

  getValueFromCfgFile "ClientConnectionMethods" "${CONFIG_FILE}"

  if [ ${ret_getValueFromCfgFile} = 1 ];
  then
    setValueAtCfgFile "${CONFIG_FILE}" "ClientConnectionMethods" "NX,SSH"
  fi
}

removeConnectionMethod ()
{
  connection_metod="$1"

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

  getValueFromCfgFile "ClientConnectionMethods" "${CONFIG_FILE}"

  if [ ${ret_getValueFromCfgFile} = 1 ] ||  [ ${ret_getValueFromCfgFile} = 2 ];
  then
    grep_out=$(${ECHOCOMMAND} "${cfg_val}" | ${GREPCOMMAND} ${connection_metod} 2>/dev/null)

    if [ "x${grep_out}" != "x" ];
    then
      new_connection_metod=$(${ECHOCOMMAND} "${cfg_val}" | ${SEDCOMMAND} -e 's/'"${connection_metod}"'//' -e 's/,,/,/' -e 's/^,//' -e 's/,$//' 2>/dev/null)
      setValueAtCfgFile "${CONFIG_FILE}" "ClientConnectionMethods" "${new_connection_metod}"
    fi
  fi
}

addConnectionMethod ()
{
  connection_metod="$1"

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

  getValueFromCfgFile "ClientConnectionMethods" "${CONFIG_FILE}"
  if [ ${ret_getValueFromCfgFile} = 1 ] ||  [ ${ret_getValueFromCfgFile} = 2 ];
  then

    grep_out=$(${ECHOCOMMAND} "${cfg_val}" | ${GREPCOMMAND} ${connection_metod} 2>/dev/null)

    if [ "x${grep_out}" = "x" ];
    then
      new_connection_metod="${cfg_val},${connection_metod}"
      setValueAtCfgFile "${CONFIG_FILE}" "ClientConnectionMethods" "${new_connection_metod}"
    fi
  fi

}

setCommandSessregKey ()
{
  setValueAtCfgFile "$CONFIG_FILE" "#CommandSessreg" "$SESSREGCOMMAND"
}

reconfigureUPnPKey ()
{
  #
  # This function is reserved only for server packages with server.lic
  #

  if [ -f ${LICENSE_FILE} ]
  then
    getLicenseAcronym

    if [ "x${LICENSE_ACRONYM}" = "x" ];
    then
      printMsg "Cannot read license acronym" "warn"

      return 0
    fi

    LICENSE_ACRONYM_CUT="${LICENSE_ACRONYM:1}"
    LICENSE_ACRONYM_CUT="${LICENSE_ACRONYM_CUT%?}"

    if [ "x${LICENSE_ACRONYM:1}" = "xS" ] || [ "x${LICENSE_ACRONYM_CUT}" = "xW" ] || \
       [ "x${LICENSE_ACRONYM_CUT}" = "xWP" ] || [ "x${LICENSE_ACRONYM_CUT}" = "xSBS" ] || \
       [ "x${LICENSE_ACRONYM_CUT}" = "xSBSP" ] ;
    then
      getValueFromCfgFile "EnableUPnP" "${CONFIG_FILE}"

      if [ ${ret_getValueFromCfgFile} = 2 ] && [ "$cfg_val" = "NX" ];
      then
        setValueAtCfgFile "${CONFIG_FILE}" "EnableUPnP" "none"
      fi
    fi
  fi
}

setSystemLogFileKey ()
{
  if [[ $(${GREPCOMMAND} "Redirect NX Server to log to a custom file instead of logging to the" "${CONFIG_FILE}") ]]; then
    ${AWKCOMMAND} '{ gsub("Redirect NX Server to log to a custom file instead of logging to the","Point the server 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("system log, usually the /var/log/messages file.","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}/var/log/server.log"
    fi
  else
    if [[ $(${GREPCOMMAND} "#SystemLogFile" "${CONFIG_FILE}") ]]; then
      setValueAtCfgFile "${CONFIG_FILE}" "#SystemLogFile" "${NX_VAR_DIR}/log/server.log"
    fi
  fi
}

setConnectPolicyKey ()
{
  if [[ ! $(${GREPCOMMAND} "# automigrate=1" "${CONFIG_FILE}") ]]; then
    ${AWKCOMMAND} '{ gsub("# autoconnect=1  reconnect automatically the user'\''s virtual desktop.","# autoconnect=1  reconnect automatically the user'\''s virtual desktop.\n#\n# automigrate=1  don'\''t connect to a virtual desktop when there is a\n#                a user already connected but disconnect and reconnect\n#                the session on the new side session migration.",$0); print $0  }' ${CONFIG_FILE} > ${CONFIG_FILE}.tmp
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  if [[ ! $(${GREPCOMMAND} "# dialog=1" "${CONFIG_FILE}") ]]; then
    ${AWKCOMMAND} '{ gsub("#                key.","#                key.\n#\n# dialog=1       display the disconnect/terminate dialog.",$0); print $0  }' ${CONFIG_FILE} > ${CONFIG_FILE}.tmp
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  getValueFromCfgFile "ConnectPolicy" "${CONFIG_FILE}"
  if [[ "${cfg_val}x" != *"dialog"*x ]]; then
    setValueAtCfgFile "${CONFIG_FILE}" "ConnectPolicy" ${cfg_val},dialog=0
  fi

  if [[ $(${GREPCOMMAND} "# automigrate=1  don't connect to a virtual desktop when there is a" "${CONFIG_FILE}") ]]; then
    ${SEDCOMMAND} -e "s/# automigrate=1  don't connect to a virtual desktop when there is a/# automigrate=1  disconnect and reconnect the virtual desktop on the/" -e "s/#                a user already connected but disconnect and reconnect/#                new side (session migration) when the user and the/" -e "s/#                the session on the new side (session migration)./#                owner of the desktop are the same./" ${CONFIG_FILE} > ${CONFIG_FILE}.tmp
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

}

getLicenseInfo ()
{
  lic_file="$1"

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

  getLicenseAcronym "${lic_file}"

  tmp=$(${AWKCOMMAND}  '/^Subscription Type/ {print $3}' "${lic_file}" 2>/dev/null)

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

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

    if [ "x${lic_subscription}" = "xNode" ];
    then
      lic_subscription="Evaluation"
    else

      isEvalPackage "${ret_getLicenseAcronym}"

      if [ ${ret_isEvalPackage} = 1 ];
      then
        lic_subscription="Evaluation"
      fi
    fi
  fi
}

updateLicenses4 ()
{
  getLicenseInfo "${LICENSE_FILE}"
  base_lic_acronym="${ret_getLicenseAcronym}"
  base_lic_sub="${lic_subscription}"

  getLicenseInfo "${LICENSE_FILE}.sample"
  new_lic_acronym="${ret_getLicenseAcronym}"
  new_lic_sub="${lic_subscription}"

  printMsg "Updating product: ${base_lic_acronym} (${base_lic_sub}) to: ${new_lic_acronym} (${new_lic_sub})" "cmd"

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

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

  printMsg "Updating product: ${base_lic_acronym} (${base_lic_sub}) to: ${new_lic_acronym} (${new_lic_sub})" "cmd"

  #
  # Disable replacing license file while updating
  # 0 - Same products;
  # 1 - Cloud Server by Enterprise Terminal Server;
  # 2 - Enterprise Server by Enterprise Terminal Server;
  # 3 - Enterprise Server by Cloud Server.
  #

  if [ "${base_lic_acronym}" = "${new_lic_acronym}" ] ||
     ( [ "${base_lic_acronym}" = "LCSE" ] && [ "${new_lic_acronym}" = "LETSE" ] ) ||
     ( [ "${base_lic_acronym}" = "LESE" ] && [ "${new_lic_acronym}" = "LETSE" ] ) ||
     ( [ "${base_lic_acronym}" = "LESE" ] && [ "${new_lic_acronym}" = "LCSE" ] )
  then

    #
    # Update package with the same product, do not use new license.
    #

    printMsg "Installation is updated to the same product type. License was not changed" "cmd"

    removeLicenseSampleFile
    removeLicenseSampleFile "${NODE_LICENSE_FILE}"

    setPermLicense

    return 0
  fi

  #
  # Existing product have Subscription license.
  #

  comparePackages "${base_lic_acronym}" "${new_lic_acronym}" "${LICENSE_FILE}" "${LICENSE_FILE}.sample"

  if [ $ret_comparePackages = 0 ];
  then
    if [ "x${base_lic_sub}" != "xEvaluation" ];
    then

      #
      # Update non-eval package with the same eval product, do not use new license.
      #

      printMsg "Update standard package with the same evaluation product. The license was not changed" "cmd"
      printMsg "Installation of a standard package is updated with the correspondent package type for evaluation. License was not changed" "cmd"

      removeLicenseSampleFile
      removeLicenseSampleFile "${NODE_LICENSE_FILE}"

      setPermLicense

      return 0
    fi
  fi

  #
  # Backup old license and use a new one.
  #

  printMsg "Installation is updated to another package type. A backup of the old license was done" "cmd"

  #
  # nxnode license file.
  #

  commandBackupMvFile "${NODE_LICENSE_FILE}" "backup" "error"

  #
  # nxserver license file.
  #

  commandBackupMvFile "${LICENSE_FILE}" "backup" "error"
  validateLicenseFile
  installLicenseFile

  #
  # Update connection method.
  #

  setConnectionMethods
}

upgradeLicenseFile ()
{
  #
  # Setting proper permissions for all licenses.
  #

  setPermLicense "${LICENSE_FILE}"

  #
  # .backup licenses.
  #

  setPermLicense "${LICENSE_FILE}.backup"
  setPermLicense "${NODE_LICENSE_FILE}.backup"

  #
  # .sample licenses.
  #

  setPermLicense "${LICENSE_FILE}.sample"
  setPermLicense "${NODE_LICENSE_FILE}.sample"

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

    #
    # Do not touch current license.
    #

    if [ ! -f "${LICENSE_FILE}" ] && [ -f "${LICENSE_FILE}.backup" ];
    then
      commandRestoreFile "${LICENSE_FILE}" "backup"
    fi

    removeLicenseSampleFile

    return 0
  fi

  if [ ! -f "${LICENSE_FILE}" ] && [ -f "${LICENSE_FILE}.backup" ];
  then
    commandRestoreFile  "${LICENSE_FILE}" "backup"
    removeLicenseSampleFile
  fi

  if [ -f "${LICENSE_FILE}" ];
  then
    if [ ! -f "${LICENSE_FILE}.sample" ];
    then
      removeLicenseSampleFile
    else
      updateLicenses4
    fi

    return 0
  fi

  tmp=$(${AWKCOMMAND} '/^Subscription Type/ {print $3}' "${LICENSE_FILE}.sample" 2>/dev/null)

  if [ "x${tmp}" != "x" ];
  then
    SUBSCRIPTION=${tmp}
  else
    return 0
  fi

  if [ ${SUBSCRIPTION} = "None" ] || [ ${SUBSCRIPTION} = "Evaluation" ];
  then
    validateLicenseFile
    installLicenseFile

    return 0
  fi

  installLicenseFile
}

isSSHSupported ()
{
  ret_isSSHSupported=0

  #
  # SSH key are shipped also with NoMachine packages since 4.1.11
  #

  isFreePackage

  if [ $ret_isFreePackage = 1 ];
  then
    SSH_DISABLED_IN_LICENSE=1
    ret_isSSHSupported=0

    return 0
  fi

  SSH_DISABLED_IN_CONFIG=1
  getValueFromCfgFile "ClientConnectionMethods" "${CONFIG_FILE}"

  if [ ${ret_getValueFromCfgFile} = 2 ] && [ "x${cfg_val}" != "x" ];
  then
    if [[ ${cfg_val} == *SSH* ]];
    then
      SSH_DISABLED_IN_CONFIG=0
      ret_isSSHSupported=1
      return 0
    fi
  fi
}

upgradeConfigFile ()
{

  ret_upgradeConfigFile=0

  #global replaceing
  ${SEDCOMMAND} -e 's/NX server/NX Server/g' \
                -e 's/NX node/NX Node/g' \
                -e 's/NX agent/NX Agent/g' \
                -e 's/NX runner/NX Runner/g' \
                -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"

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

    ${CATCOMMAND} "${CONFIG_FILE}.aux" >> "${CONFIG_FILE}"
    commandRm "${CONFIG_FILE}.aux"
    #printMsgDebug "upgradeConfigFile: Added copyright..."
  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"
    #printMsgDebug "upgradeConfigFile: Updated ConfigFileVersion..."
  fi

#SessionLogLevel
  command="${GREPCOMMAND} '[#]*SessionLogLevel *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Note, anyway, that NX Server uses level 6 in the syslog to log/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Note, anyway, that NX Server uses level 6 in the syslog to log/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    #${SEDCOMMAND} -e '/ *# *Note, anyway, that NX Server uses level 6 in the syslog to log/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    #commandRestoreFile "${CONFIG_FILE}" "tmp"
    #${SEDCOMMAND} -e '/ *# *Note, anyway, that NX Server uses level 6 in the syslog to log/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    #commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Note, anyway, that NX Server uses level 6 in the syslog to log the.*/# Note that NX Server uses level 6 in the syslog to log the event.\
# This is intended to override settings on the local syslog configur-\
# ation that would prevent the event from being actually logged./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "SessionLogLevel"
  fi

  command="${GREPCOMMAND} '[#]*SSHDPort *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Specify the TCP port where the NX Server SSHD daemon is running.*/# Specify the TCP port where the SSHD daemon is listening on the NX\
# Server host machine./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "SSHDPort"
  fi

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

    ${SEDCOMMAND} -e 's/ *# *DisplayBase 1000/#DisplayBase 1001/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  upgradeKey "DisplayLimit"


  upgradeKey "SessionLimit"
    #change name to ConnectionsLimit
    ${SEDCOMMAND} -e 's/SessionLimit/ConnectionsLimit/' -e 's/.*Set.*maximum *number.*concurrent *NX *sessions.*/# Set the maximum number of concurrent connections./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"


  command="${GREPCOMMAND} '[#]*SessionUserLimit *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/^ *# *Set the maximum number of concurrent NX sessions that can be run by/ {n; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/^ *# *Set the maximum number of concurrent NX sessions that can be run by/ {n; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/^ *# *Set the maximum number of concurrent NX sessions that can be run by/ {n; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/^ *# *Set the maximum number of concurrent NX sessions that can be run by/ {n; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Set the maximum number of concurrent NX sessions that can be run by.*/# Specify the maximum number of concurrent connections that can be\
# run by a single user./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "SessionUserLimit"

    #change name to ConnectionsUserLimit
    ${SEDCOMMAND} -e 's/SessionUserLimit/ConnectionsUserLimit/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

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

    ${SEDCOMMAND} -e '/ *# *The default value, 2592000, lets NX Server keep session data/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *The default value, 2592000, lets NX Server keep session data/# The default value, 2592000 seconds, lets NX Server keep session data\
# for 30 days./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "SessionHistory"
  fi

  command="${GREPCOMMAND} '[#]*EnableAdministratorLogin *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Allow the root user to run NX sessions.*/# Allow the root user (or Administrator on a Windows machine) to\
# run NX sessions./' \
                  -e 's/NX Server forbids a NX user to log as user/NX Server forbids an NX user to log in as user/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "EnableAdministratorLogin"
  fi

  command="${GREPCOMMAND} '[#]*EnableAutokillSessions *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Allow the server to terminate oldest suspended sessions/# Allow NX Server to terminate oldest disconnected sessions/' \
                  -e 's/Enabled. Enable the automatic kill of the suspended/Enabled. Enable the automatic kill of the disconnected/' \
                  -e 's/Disabled. Suspended sessions are never terminated/Disabled. Disconnected sessions are never terminated/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e '/^ *# *When this option is set, and the server capacity has been reached/ {n; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/^ *# *When this option is set, and the server capacity has been reached/ {n; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/^ *# *When this option is set, and the server capacity has been reached/ {n; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e 's/^ *# *When this option is set, and the server capacity has been reached.*/# When this option is set and the maximum number of concurrent sessions\
# has been reached, the server will kill the oldest disconnected sessions to\
# make room for the new session./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "EnableAutokillSessions"
  fi

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

    upgradeKey "EnablePersistentSession"
  fi

  upgradeKey "DisablePersistentSession" "1"

  upgradeKey "EnableClipboard"
  upgradeKey "EnableUserDB"

  command="${GREPCOMMAND} '[#]*EnablePasswordDB *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *nect to the NX Server by setting EnableUserDB to 1 and adding/# nect to NX Server by setting EnableUserDB to 1 and adding/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    upgradeKey "EnablePasswordDB"
  fi

  #upgradeKey "ServerSensorPort"

  #upgradeKey "EnableNodeMonitoring"
  #upgradeKey "NodeResponseTimeout"

  upgradeKey "RoundRobinXdmList"
  upgradeKey "EnableRoundRobinXdmQuery"
  upgradeKey "EnableIndirectXdmQuery"
  upgradeKey "EnableDirectXdmQuery"
  upgradeKey "EnableBroadcastXdmQuery"

  command="${GREPCOMMAND} '[#]*CommandSessreg *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Specify path and name of the command '\'sessreg\''.*/# Specify path and name of the command '\'sessreg\'' for managing utmp and\
# wtmp entries for non-init clients./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "CommandSessreg"

    ${SEDCOMMAND} -e 's| *# *CommandSessreg /usr/X11R6/bin/sessreg|#CommandSessreg /usr/X11/bin/sessreg|' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  command="${GREPCOMMAND} '[#]*SSHAuthorizedKeys *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -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 "SSHAuthorizedKeys"
  fi

  command="${GREPCOMMAND} '[#]*SSHDCheckIP *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Accept or refuse the NX Client connection if SSHD does not export.*/# Accept or refuse the client connection if SSHD does not export/' \
                  -e 's/Check the remote IP and don'\''t accept the connection/Check the remote IP and do not accept the connection if it/' \
                  -e 's/if it can'\''t be determined/can'\''t be determined/' \
                  -e 's/Check the remote IP and accept the connection even if/Check the remote IP and accept the connection even if the/' \
                  -e 's/the remote IP is not provided/remote IP is not provided/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "SSHDCheckIP"
  fi

  upgradeKey "GuestName"
  upgradeKey "BaseGuestUserId"
  upgradeKey "GuestUserIdLimit"
  upgradeKey "GuestUserGroup"
  upgradeKey "GuestUserLimit"
  upgradeKey "GuestUserConnectionLimit"

  command="${GREPCOMMAND} '[#]*GuestUserAccountExpiry *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/Set for how long the NX Server has to retain NX guest users accounts/Set for how long NX Server has to retain NX guest users accounts/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e '/The default value, 2592000, lets NX Server keep guest users accounts/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *The default value, 2592000, lets NX Server keep guest users accounts/# The default value, 2592000 seconds, lets NX Server keep guest users\
# accounts for 30 days./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "GuestUserAccountExpiry"
  fi

  command="${GREPCOMMAND} '[#]*GuestConnectionExpiry *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/Set for how long the NX Server has to keep alive a NX guest/Set for how long NX Server has to keep alive a NX guest/' \
                  -e 's/session. When the time is expired/session. When the time has expired/' \
                  -e 's/NX guest user.s session is never terminated/NX guest user session is never terminated/' \
                  -e 's/Keep alive NX guest user. session for this amount/Keep NX guest user session live for this number/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "GuestConnectionExpiry"
  fi

  command="${GREPCOMMAND} '[#]*GuestUserAllowSuspend *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Enable or disable possibility for NX guest users to suspend sessions.*/# Enable or disable possibility for NX guest users to disconnect their\
# sessions:/' \
                  -e 's/The NX Server lets NX guest users suspend sessions/NX Server lets NX guest users disconnect sessions/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "GuestUserAllowSuspend"
    ${SEDCOMMAND} -e 's/GuestUserAllowSuspend/GuestUserAllowDisconnect/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  command="${GREPCOMMAND} '[#]*GuestUserHome *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e '/ *# *Set the home directory for NX guest users/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/ *# *Set the home directory for NX guest users/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Set the home directory for NX guest users.*/# Set the home directory for NX guest users. Provide an empty value\
# between double quotes to let NX Server create the guest user'\''s home\
# in the default directory set on the system./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "GuestUserHome" "1"
  fi

  command="${GREPCOMMAND} '[#]*EnableGuestWipeout *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Enable or disable removing the guest user from the system when the/# Enable or disable removing the NX guest user from the system when the/' \
                  -e 's/When the guest account is expired, the NX Server will/When the guest account is expired, NX Server will/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "EnableGuestWipeout"
  fi

  command="${GREPCOMMAND} '[#]*EnableGuestQuota *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *Allow the server to set disk quota for the guest accounts:/# Allow the server to set disk quota for the NX guest accounts:/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "EnableGuestQuota"
  fi

  upgradeKey "GuestQuotaProtoname"
  upgradeKey "GuestQuotaInodeSoftlimit"
  upgradeKey "GuestQuotaInodeHardlimit"
  upgradeKey "GuestQuotaBlockSoftlimit"
  upgradeKey "GuestQuotaBlockHardlimit"
  upgradeKey "GuestQuotaInodeGracePeriod"
  upgradeKey "GuestQuotaBlockGracePeriod"
  upgradeKey "GuestQuotaFilesystems"
  upgradeKey "UserId"

  command="${GREPCOMMAND} '[#]*UserGroup *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *specified, the NX Server will create the account with the default/# specified, NX Server will create the account with the default/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    upgradeKey "UserGroup"
  fi

  command="${GREPCOMMAND} '[#]*UserHome *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/ *# *the NX Server will create the user'\''s home in the default directory/# NX Server will create the user'\''s home in the default directory/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    upgradeKey "UserHome" "1"
  fi

  command="${GREPCOMMAND} '[#]*EnableSessionShadowing *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/EnableSessionShadowing/VirtualDesktopSharing/' \
                  -e 's/ *# *Allow session shadowing on this server:.*/# Allow the user to connect to a virtual desktop:/' \
                  -e 's/Enabled. *Each user can require to attach to an already running.*/Enabled. Each user can request to connect to a/' \
                  -e 's/session. The session owner has to accept connection.*/virtual desktop./' \
                  -e 's/Disabled. Session shadowing is forbidden.*/Disabled. Connections to a virtual desktop are\
#    forbidden./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "VirtualDesktopSharing"
  fi

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

    ${SEDCOMMAND} -e '/Allow session shadowing in interactive mode/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow session shadowing in interactive mode/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow session shadowing in interactive mode/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow session shadowing in interactive mode/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow session shadowing in interactive mode/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow session shadowing in interactive mode/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Allow session shadowing in interactive mode.*/# Set the interaction level for the session connected to a virtual\
# desktop:\
#\
# 0: View-only. The session is connected to the desktop in\
#    view-only mode, i.e. the user can'\''t interact with the\
#    virtual desktop.\
#\
# 1: Restricted. User connected to the virtual desktop can\
#    interact with the desktop except for resize operations.\
#\
# 2: Interactive. User connected to the virtual desktop has\
#    full interaction with the desktop./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "VirtualDesktopMode"

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

    getValueFromCfgFile "VirtualDesktopMode" "${CONFIG_FILE}"
    if [ ${ret_getValueFromCfgFile} = 2 ];
    then
      if [ ${cfg_val} != 0 ];
      then
        cfg_val=2
      fi

      setValueAtCfgFile "${CONFIG_FILE}" "VirtualDesktopMode" "${cfg_val}"
    fi
  fi

  command="${GREPCOMMAND} '[#]*VirtualDesktopSharingAuthorization *= ' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/VirtualDesktopSharingAuthorization/VirtualDesktopAuthorization/' \
                  -e 's/Enable or disable NX Server requiring authorization to the owner/Enable or disable NX Server requesting authorization to the owner of/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e '/of the NX session before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the NX session before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the NX session before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the NX session before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the NX session before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the NX session before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the NX session before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *of the NX session before sharing the session.*/# the virtual desktop before connecting.\
#\
# 1: Enabled. NX Server asks for authorization to the owner\
#    of the virtual desktop before trying to connect.\
#\
# 0: Disabled. NX Server tries to connect to the virtual\
#    desktop without the need for any authorization from the\
#    desktop'\''s owner./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "VirtualDesktopAuthorization"

    ${SEDCOMMAND} -e 's/ *# *VirtualDesktopAuthorization.*/#VirtualDesktopAuthorization 1/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

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

    ${SEDCOMMAND} -e '/Allow desktop sharing on this server:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing on this server:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing on this server:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing on this server:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing on this server:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Allow desktop sharing on this server:.*/# Allow the user to connect to the physical desktop:\
#\
# 1: Enabled. Each user can request to connect to the\
#    physical desktop.\
#\
# 0: Disabled. Connections to the physical desktop are\
#    forbidden./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "PhysicalDesktopSharing"
  fi

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

    ${SEDCOMMAND} -e '/Allow desktop sharing in interactive mode:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing in interactive mode:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing in interactive mode:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing in interactive mode:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing in interactive mode:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/Allow desktop sharing in interactive mode:/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *Allow desktop sharing in interactive mode:.*/# Set the interaction level for the session connected to the physical\
# desktop:\
#\
# 0: View-only. The session is connected to the desktop in\
#    view-only mode, i.e. the user can'\''t interact with the\
#    physical desktop.\
#\
# 1: Interactive. User connected to the physical desktop has\
#    full interaction with the desktop./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "PhysicalDesktopMode"
  fi

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

    ${SEDCOMMAND} -e '/of the desktop before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the desktop before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the desktop before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the desktop before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the desktop before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the desktop before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
    ${SEDCOMMAND} -e '/of the desktop before sharing the session/ {p; N; d;}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    ${SEDCOMMAND} -e 's/ *# *of the desktop before sharing the session.*/# the physical desktop before connecting.\
#\
# 1: Enabled. NX Server asks for authorization to the owner\
#    of the physical desktop before trying to connect.\
#\
# 0: Disabled. NX Server tries to connect to the physical\
#    desktop without the need for any authorization from the\
#    desktop'\''s owner./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "PhysicalDesktopAuthorization"

    ${SEDCOMMAND} -e 's/ *# *PhysicalDesktopAuthorization.*/#PhysicalDesktopAuthorization 1/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  upgradeKey "UserScriptBeforeLogin" "1"
  upgradeKey "UserScriptAfterLogin" "1"
  upgradeKey "UserScriptBeforeSessionStart" "1"
  upgradeKey "UserScriptAfterSessionStart" "1"
  upgradeKey "UserScriptBeforeSessionClose" "1"
  upgradeKey "UserScriptAfterSessionClose" "1"
  upgradeKey "UserScriptBeforeSessionReconnect" "1"
  upgradeKey "UserScriptAfterSessionReconnect" "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/# the session is disconnected. The script can accept session ID/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"

    upgradeKey "UserScriptBeforeSessionSuspend" "1"

    ${SEDCOMMAND} -e 's/UserScriptBeforeSessionSuspend/UserScriptBeforeSessionDisconnect/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

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

    upgradeKey "UserScriptAfterSessionSuspend" "1"

    ${SEDCOMMAND} -e 's/UserScriptAfterSessionSuspend/UserScriptAfterSessionDisconnect/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  upgradeKey "UserScriptBeforeSessionFailure" "1"
  upgradeKey "UserScriptAfterSessionFailure" "1"
  upgradeKey "UserScriptBeforeCreateUser" "1"
  upgradeKey "UserScriptAfterCreateUser" "1"
  upgradeKey "UserScriptBeforeDeleteUser" "1"
  upgradeKey "UserScriptAfterDeleteUser" "1"
  upgradeKey "UserScriptBeforeDisableUser" "1"
  upgradeKey "UserScriptAfterDisableUser" "1"
  upgradeKey "UserScriptBeforeEnableUser" "1"
  upgradeKey "UserScriptAfterEnableUser" "1"

  insertKeytoConfigFile "SystemLogFile" "\n\
#\n\
# Point the server 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 "SSHClient" "\n\
#\n\
# Specify path to the SSH client.\n\
#\n\
#SSHClient /usr/bin/ssh" "ScriptAfterServerDaemonStop"

  insertKeytoConfigFile "StartHTTPDaemon" "\n\
#\n\
# Enable or disable starting the NoMachine HTTP service. If enabled, the service\n\
# will be started automatically at every reboot.\n\
#\n\
# 1: Automatic. Enable automatic starting of the HTTP server.\n\
#\n\
# 0: Manual. Disable automatic starting of the HTTP server.\n\
#    The server can be started manually.\n\
#\n\
#StartHTTPDaemon Automatic" "ServerSensorPort"

  insertKeytoConfigFile "UpdateFrequency" "\n\
#\n\
# Set how often NoMachine must check for updates on the repository.\n\
# Default value, 172800 seconds, allow to check once every two days.\n\
# To disable check for updates, set this key to 0.\n\
#\n\
#UpdateFrequency 172800" "SystemLogFile"

  insertKeytoConfigFile "NXPort" "\n\
#\n\
# Specify the TCP port where the NX service is listening.\n\
#\n\
#NXPort 4000" "UpdateFrequency"

  insertKeytoConfigFile "NXTCPUPnPPort" "\n\
#\n\
# Specify the port where the NX UDP service will be redirected using NAT-\n\
# PMP or UPnP to allow end-users to connect to the server through a\n\
# firewall.\n\
#\n\
#NXTCPUPnPPort \\\"\\\"" "EnableUPnPSession"

  insertKeytoConfigFile "EnableUPnP" "\n\
#\n\
# Enable support for NAT-PMP and UPnP networking protocols to redirect\n\
# a port from server side to allow end-users to connect to the server\n\
# through a firewall. Accepted values are:\n\
#\n\
# NX:   Redirect port of the nxd service.\n\
#\n\
# SSH:  Redirect port of the SSH server.\n\
#\n\
# HTTP: Redirect port of the HTTP server.\n\
#\n\
# none: Do not redirect port. Connections via NX, SSH or HTTP\n\
#       protocol are possible only if NoMachine host and user's\n\
#       machine are on the same LAN or server has a public IP.\n\
#\n\
#EnableUPnP none" "NXPort"

  insertKeytoConfigFile "SSHUPnPPort" "\n\
#\n\
# Specify the port where the SSHD service will be redirected using\n\
# NAT-PMP or UPnP to allow end-users to connect to the server through\n\
# a firewall.\n\
# \n\
#SSHUPnPPort \"\"" "EnableUPnP"

  insertKeytoConfigFile "HTTPUPnPPort" "\n\
#\n\
# Specify the port where the HTTP service will be redirected using\n\
# NAT-PMP or UPnP to allow end-users to connect to the server through\n\
# a firewall.\n\
# \n\
#HTTPUPnPPort \"\"" "SSHUPnPPort"

  insertKeytoConfigFile "UDPPort" "\n\
#\n\
# Specify a port range, in the form of minport-maxport, to use UDP\n\
# communication for multimedia data. Alternatively, specify a comma-\n\
# separated list of ports or a single port. In this last case, only\n\
# one connection will be able to use UDP at any given time. As a note,\n\
# the Internet Assigned Numbers Authority (IANA) suggests the range\n\
# 49152 to 65535 for dynamic or private ports.\n\
#\n\
#UDPPort 4011-4999" "SSHUPnPPort"

  insertKeytoConfigFile "AutomaticDisconnection" "\n\
#\n\
# Enable or disable NX Server requests to the connected user to make\n\
# room for an incoming user when the maximum number of allowed\n\
# connections is reached.\n\
#\n\
# 1: Enabled. The server automatically disconnects the connected\n\
#    user to make room for the connecting user.\n\
#\n\
# 0: Disabled. The server requests authorization to the user\n\
#    already connected before making room for the incoming\n\
#    user.\n\
#\n\
#AutomaticDisconnection 0" "EnableAutokillSessions"

  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, SSH and HTTP.\n\
#\n\
ClientConnectionMethods NX,SSH" "StartHTTPDaemon"

  insertKeytoConfigFile "LoadBalancingAlgorithm" "\n\
#\n\
# Specify the algorithm to be used for selecting the node. Accepted\n\
# values are:\n\
#\n\
# round-robin:  the server applies a plain round-robin algorithm to\n\
#               choose the node or a weighted round-robin algorithm\n\
#               if weight has been specified for each node. This is\n\
#               the default.\n\
#\n\
# custom:       the server uses the custom load-balancing algorithm\n\
#               specified in the NodeSelectionScript key.\n\
#\n\
# load-average: the server chooses the node with the minimum load\n\
#               average provided by the system.\n\
#\n\
# system-load:  the server selects the node with the lowest system\n\
#               load calculated according to the algorithm specified\n\
#               in the nxreportsystemload.sh script set on the node.\n\
#\n\
#LoadBalancingAlgorithm round-robin" "EnableBroadcastXdmQuery"

  insertKeytoConfigFile "NodeSelectionScript" "\n\
#\n\
# Specify path and name to the script providing the load-balancing al-\n\
# gorithm.\n\
#\n\
#NodeSelectionScript \"\"" "LoadBalancingAlgorithm"

  insertKeytoConfigFile "ConnectPolicy" "\n\
#\n\
# Specify policies as a comma-separated list of options to tune the\n\
# behaviour of clients 4 or higher and restore behaviors typical of\n\
# version 3.x. Options accept value 1 (enabled) and 0 (disabled).\n\
# This is the list of the available options:\n\
#\n\
# autocreate=1   run a new virtual desktop automatically when the ses-\n\
#                sion type is pre-defined in the player configuration.\n\
#\n\
# autoconnect=1  reconnect automatically the user's virtual desktop.\n\
#\n\
# automigrate=1  disconnect and reconnect the virtual desktop on the\n\
#                new side (session migration) when the user and the\n\
#                owner of the desktop are the same.\n\
#\n\
# desktop=1      list all desktop types set in the \"AvailableSessionTypes\"\n\
#                key.\n\
#\n\
# dialog=1       display the disconnect/terminate dialog.\n\
#\n\
#ConnectPolicy autocreate=1,autoconnect=1,automigrate=1,desktop=0,dialog=0" "SSHClient"

#  insertKeytoConfigFile "InstallationType" "\n\
#\n\
# Specify whether this installation can accept requests to connect\n\
# from other NoMachine computers, or if it must be a player machine\n\
# only. Accepted values are:\n\
#\n\
# player: This installation permits access to other computers over the\n\
#         network.\n\
#\n\
# server: This host accepts incoming connections from other players.\n\
#\n\
# node:   This host accepts incoming connections from NoMachine\n\
#         servers as part of a multi-node environment.\n\
#\n\
#InstallationType player" "ConnectPolicy"


  insertKeytoConfigFile "ConnectionsLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent connections reaches that value. This key\n\
# must be used in conjunction with the ConnectionsLimit key.\n\
#\n\
#ConnectionsLimitAlert 0" "ConnectionsLimit"

  insertKeytoConfigFile "ConnectionsUserLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent users reaches that value. This key\n\
# must be used in conjunction with the ConnectionsUserLimit key.\n\
#\n\
#ConnectionsUserLimitAlert 0" "ConnectionsUserLimit"

  insertKeytoConfigFile "VirtualDesktopsLimit" "\n\
#\n\
# Set the maximum number of concurrent virtual desktops.\n\
#\n\
#VirtualDesktopsLimit 20" "ConnectionsUserLimitAlert"

  insertKeytoConfigFile "VirtualDesktopsLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent users reaches that value. This key\n\
# must be used in conjunction with the VirtualDesktopsLimit key.\n\
# The alert threshold should not be higher than the number of virtual\n\
# desktops allowed by the license.\n\
#\n\
#VirtualDesktopsLimitAlert 0" "VirtualDesktopsLimit"

  insertKeytoConfigFile "VirtualDesktopsUserLimit" "\n\
#\n\
# Specify the maximum number of concurrent Linux virtual desktops\n\
# that can be run by a single user. By default a user can run as\n\
# many virtual desktops as they are allowed on the server. By setting\n\
# this value to 1, user has to terminate their disconnected virtual\n\
# desktop before starting a new one.\n\
#\n\
#VirtualDesktopsUserLimit 20" "VirtualDesktopsLimitAlert"

  insertKeytoConfigFile "VirtualDesktopsUserLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent users reaches that value. This key\n\
# must be used in conjunction with the VirtualDesktopsUserLimit key.\n\
#\n\
#VirtualDesktopsUserLimitAlert 0" "VirtualDesktopsUserLimit"

  insertKeytoConfigFile "UserScriptAfterLimitAlarm" "\n\
#\n\
# Specify absolute path of the custom script to be executed when any\n\
# of the threshold alarms set for users or connections limits is\n\
# reached. The script can accept username, client IP, type of alarm\n\
# (for connections, users connections, virtual desktops and users\n\
# virtual desktops limit) as its input.\n\
#\n\
#UserScriptAfterLimitAlarm \"\"" "VirtualDesktopsUserLimitAlert"

  insertKeytoConfigFile "ClientMenuConfiguration" "\n\
#\n\
# Configure behavior of the NoMachine menu to be displayed inside the\n\
# session: hide the welcome panels shown at session startup, prevent\n\
# users from changing settings or use specific services. Default is\n\
# 'all', welcome panels are shown and the menu can be used without\n\
# restrictions. Set this key to 'none' for hiding both welcome panels\n\
# and the NoMachine menu (clicking on the page peel or pressing ctrl+\n\
# alt+0 will not open it). Give a comma-separated list of values to\n\
# indicate which items should be made available to users.\n\
#\n\
# Available values for client and web sessions are: welcome,input,\n\
# display,display-mode,display-settings,connection. Client sessions\n\
# support also: devices,devices-disk,devices-printer,devices-usb,\n\
# devices-network,devices-smartcard,audio,audio-settings,mic,mic-\n\
# settings,recording. For web sessions instead it's possible to set\n\
# also: keyboard,clipboard.\n\
#\n\
#ClientMenuConfiguration all" "UserScriptAfterLimitAlarm"

  removeOldOptionsFromCfg3
}

cleanRestrictedDirectory ()
{
  if [ -d "${NX_ROOT}/restricted" ];
  then
    if [ -f "${NX_ROOT}/restricted/nxaddprinter.sh" ];
    then
      commandRm "${NX_ROOT}/restricted/nxaddprinter.sh" "cmd"
    fi
    if [ -f "${NX_ROOT}/restricted/nxtmpperm.sh" ];
    then
      commandRm "${NX_ROOT}/restricted/nxtmpperm.sh" "cmd"
    fi
    commandRmDir "${NX_ROOT}/restricted" "cmd"
  fi
}

cleanShareDirectory ()
{
  nxfiles="knotifyrc.artsd knotifyrc.esd mcoprc nxagent.xpm nxdesktop.xpm nxviewer.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

  command="${RMCOMMAND} -rf '${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_Portal_Server_Installation_and_Configuration_Guide.pdf'"
  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

  rm -f "${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_4.x_-_Server_Administrator's_Guide_-_Advanced_Functions.pdf" "cmd"
  rm -f "${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_4.x_Server_Administrator_Guide_Advanced_Functions.pdf" "cmd"

  commandRmIfExist "${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_4.1_-_Server_Administrator's_Guide.pdf" "cmd"
  commandRmIfExist "${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_4.1_Server_Administrator_Guide.pdf" "cmd"

  commandRmIfExist "${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_4.x_or_later_-_Server_Guide_-_Advanced_Functions.pdf" "cmd"
  commandRmIfExist "${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_4.x_or_later_-_Server_Guide.pdf" "cmd"

  commandRmIfExist "${NX_ROOT}/share/documents/guides/NoMachine_Enterprise_Products_Cloud_Server_Installation_and_Configuration_Guide.pdf" "cmd"
  commandRmIfExist "${NX_ROOT}/share/documents/guides/NoMachine_Terminal_Server_Node_Installation_Guide.pdf" "cmd"

  commandRmIfExist "${NX_ROOT}/share/documents/guides/Guide_to_the_Functionality_in_the_Menu_Panel.pdf" "cmd"
  commandRmIfExist "${NX_ROOT}/share/documents/guides/Guide_to_Authentication_Methods_for_NoMachine_4.x.pdf" "cmd"

  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_es_ES" "cmd"
  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_fr_FR" "cmd"
  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_de_DE" "cmd"
  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_it_IT" "cmd"
  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_pl_PL" "cmd"
  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_pt_PT" "cmd"
  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_et_ET" "cmd"
  commandRmIfExist "${NX_ROOT}/share/locale/nxserver_ru_RU" "cmd"
}

copySessionHistory ()
{
  if [ -d "${NX_VAR_DIR}/finishedSession" ];
  then
   runCommand "${MVCOMMAND} '${NX_VAR_DIR}/finishedSession/*' '${NX_VAR_DIR}/db/closed'" "Cannot archiving session history" "warn"
  fi

  if [ -d "${NX_VAR_DIR}/failedSession" ]
  then
    runCommand "${MVCOMMAND} '${NX_VAR_DIR}/failedSession/*' '${NX_VAR_DIR}/db/failed'" "Cannot archiving failed session history" "warn"
  fi
}

cleanNXDb ()
{
  if [ -f "${NX_VAR_DIR}/sessions/.counter" ];
  then
    runCommand "${RMCOMMAND} -f '${NX_VAR_DIR}/sessions/.counter'" "Cannot remove '${NX_VAR_DIR}/sessions/.counter' file"
  fi

  if [ -f "${NX_VAR_DIR}/db/broadcast" ];
  then
    runCommand "${RMCOMMAND} -f '${NX_VAR_DIR}/db/broadcast'" "Cannot remove '${NX_VAR_DIR}/db/broadcast' file"
  fi

  if [ -d "${NX_VAR_DIR}/db/running" ];
  then
    if [ -f "${NX_VAR_DIR}/db/running/display{last}" ];
    then
      runCommand "${RMCOMMAND} -f '${NX_VAR_DIR}/db/running/display{last}'" "Cannot remove '${NX_VAR_DIR}/db/running/display{last}' file"
    fi
    command="${RMCOMMAND} -f '${NX_VAR_DIR}/db/running/session'*"
    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

    commandRmDirRecursively "${NX_VAR_DIR}/db/running" "cmd"
  fi

  if [ -d "${NX_VAR_DIR}/db/failed" ];
  then
    command="${RMCOMMAND} -f '${NX_VAR_DIR}/db/failed/session'*"
    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

    commandRmDirRecursively "${NX_VAR_DIR}/db/failed" "cmd"

  fi

  if [ -d "${NX_VAR_DIR}/db/closed" ];
  then
    command="${RMCOMMAND} -f '${NX_VAR_DIR}/db/closed/session'*"
    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

    commandRmDirRecursively "${NX_VAR_DIR}/db/closed" "cmd"

  fi

  if [ -d "${NX_VAR_DIR}/db/unknown" ];
  then
    command="${RMCOMMAND} -f '${NX_VAR_DIR}/db/unknown/session'*"
    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

    commandRmDirRecursively "${NX_VAR_DIR}/db/unknown" "cmd"
  fi

  if [ -f "${NX_VAR_DIR}/broadcast.txt" ];
  then
    runCommand "${RMCOMMAND} -f '${NX_VAR_DIR}/broadcast.txt'" "Cannot remove '${NX_VAR_DIR}/broadcast.txt' file"
  fi

  if [ -f "${NX_VAR_DIR}/sessions/.lock" ];
  then
    runCommand "${RMCOMMAND} -f '${NX_VAR_DIR}/sessions/.lock'" "Cannot remove '${NX_VAR_DIR}/sessions/.lock'"
  fi
}

getHello ()
{
  #
  # 1 - Auth key (RSA or DSA)
  #

  KEY_FILE="${1}"

  commandInstall "root" "${ROOTGNAME}" "400" "${KEY_FILE}" "${KEY_FILE}.prv" "warn"

  "${ECHOCOMMAND}" -e "quit\n" > /tmp/exit_file

  ret_getHello=$("${SSHClient}" -l ${USER_NX} -p $SSHDPort -i "${KEY_FILE}.prv" \
               -T -x -2 -o 'RhostsAuthentication no' -o 'PasswordAuthentication no'\
               -o 'RSAAuthentication yes' -o 'RhostsRSAAuthentication no'\
               -o 'StrictHostKeyChecking no' -o 'NumberOfPasswordPrompts 0' \
               127.0.0.1 < /tmp/exit_file 2>&1)

  "${RMCOMMAND}" -rf /tmp/exit_file

  getHello_exit_code=${?}
  commandRm "${KEY_FILE}.prv"  "warn"
}

checkSSHConnection ()
{
  KEY_FILE_DSA="$1"
  KEY_FILE_RSA="$2"
  AUTHORIZED_KEYS="$3"

  ret_checkSSHConnection="0"

  commandInstall "$USER_NX" "$USER_NX" "600" "$KEY_FILE_DSA.pub" "$AUTHORIZED_KEYS" "error"

  "$SEDCOMMAND" '1s|^|no-port-forwarding,no-agent-forwarding,command="/etc/NX/nxserver --login" |' "$AUTHORIZED_KEYS" > "$AUTHORIZED_KEYS.tmp"

  commandRestoreFile "$AUTHORIZED_KEYS" "tmp"

  getHello "${KEY_FILE_DSA}"

  commandRm "$AUTHORIZED_KEYS"  "warn"

  if [ "x$getHello_exit_code" = "x255" ];
  then

    commandInstall "$USER_NX" "$USER_NX" "600" "$KEY_FILE_RSA.pub" "$AUTHORIZED_KEYS" "error"

    "$SEDCOMMAND" '1s|^|no-port-forwarding,no-agent-forwarding,command="/etc/NX/nxserver --login" |' "$AUTHORIZED_KEYS" > "$AUTHORIZED_KEYS.tmp"

    commandRestoreFile "$AUTHORIZED_KEYS" "tmp"

    getHello "${KEY_FILE_RSA}"

    commandRm "$AUTHORIZED_KEYS"  "warn"

    if [ "x$getHello_exit_code" != "x255" ];
    then
      ret_checkSSHConnection="1"
    fi
  else
    ret_checkSSHConnection="1"
  fi
}

setSSHAuthorizedKeysValue ()
{

  KEY_FILE_DSA="${NX_ROOT}/etc/keys/node.localhost.id_dsa"
  KEY_FILE_RSA="${NX_ROOT}/etc/keys/node.localhost.id_rsa"

  SSHDPort="22"

  getValueFromCfgFile "SSHDPort" "${CONFIG_FILE}"

  if [ "x$ret_getValueFromCfgFile" = "x1" ] ||
     [ "x$ret_getValueFromCfgFile" = "x2" ];
  then
    SSHDPort="$cfg_val"
  fi

  SSHClient="ssh"

  getValueFromCfgFile "SSHClient" "${CONFIG_FILE}"

  if [ ${ret_getValueFromCfgFile} = 1 ];
  then
    SSHClient="${cfg_val}"
  fi

  checkSSHConnection "$KEY_FILE_DSA" "$KEY_FILE_RSA" "$NXUSERHOME/nx/.ssh/authorized_keys"

  if [ "x$ret_checkSSHConnection" = "x1" ];
  then
    setValueAtCfgFile "$CONFIG_FILE" "SSHAuthorizedKeys" "authorized_keys"
  else

    checkSSHConnection "$KEY_FILE_DSA" "$KEY_FILE_RSA" "$NXUSERHOME/nx/.ssh/authorized_keys2"

    if [ "x$ret_checkSSHConnection" = "x1" ];
    then
      setValueAtCfgFile "$CONFIG_FILE" "SSHAuthorizedKeys" "authorized_keys2"
    fi

  fi
}

checkSSHD ()
{
  isSSHSupported

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

    KEY_FILE_DSA="${NX_ROOT}/share/keys/server.id_dsa.key"
    KEY_FILE_RSA="${NX_ROOT}/share/keys/server.id_rsa.key"

    tmp=$(${AWKCOMMAND} -F'"' '/^SSHDPort/ {print $2}' "${CONFIG_FILE}" 2>/dev/null)

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

    SSHClient="ssh"

    getValueFromCfgFile "SSHClient" "${CONFIG_FILE}"

    if [ ${ret_getValueFromCfgFile} = 1 ];
    then
      SSHClient="${cfg_val}"
    fi

    getHello "${KEY_FILE_RSA}"
    resultNXssh=${getHello_exit_code}

    #
    # If both (RSA and DSA) keys will failed
    # we are considering exit codes and output
    # from command using RSA.
    #

    ret_getHello_rsa="${ret_getHello}"
    resultNXssh_rsa="${resultNXssh}"

    if [ ${resultNXssh} != 0 ];
    then
      getHello "${KEY_FILE_DSA}"
      resultNXssh=${getHello_exit_code}

      if [ ${resultNXssh} != 0 ];
      then
        ret_getHello="${ret_getHello_rsa}"
        resultNXssh="${resultNXssh_rsa}"
      fi
    fi

    result=$(${ECHOCOMMAND} "${ret_getHello}" | ${GREPCOMMAND} -c "NX> 105" 2>&1)

    if [ $? != 0 ];
    then

      #
      # NXSSH_RCODE can have two values.
      #
      # 0 - normal success exit code.
      #
      # 255 - on solaris because of ssh bug.
      #

      if [ ${resultNXssh} -ne ${NXSSH_RCODE} ];
      then

        tmp=$(${ECHOCOMMAND} "${ret_getHello}" | ${GREPCOMMAND} -v "NX>" 2>&1)
        tmp2=$(${PRINTFCOMMAND} "%.4s" "${tmp}")

        if [ "${tmp2}" = "ssh:" ];
        then

          printMsgNoDot "Error when trying to connect to NoMachine server. Error is:"          "warn"
          printMsgNoDot "$tmp"                                                                 "warn"
          printMsgNoDot "NX has been configured to use the SSH server on default port"         "warn"
          printMsgNoDot "$SSHDPort but no SSH daemon is listening on this port. When the"      "warn"
          printMsgNoDot "installation completes, please ensure that SSHD is installed"         "warn"
          printMsgNoDot "and is up and running. If you want to contact SSHD daemon on"         "warn"
          printMsgNoDot "a port different from 22, you need to configure NoMachine server and" "warn"
          printMsgNoDot "node accordingly. More information is available on the NoMachine"     "warn"
          printMsgNoDot "Knowledge Base at: https://www.nomachine.com/support"                 "warn"

        elif [ -f "${FILE_AUTHORIZED_KEYS}" ];
        then

          printMsgNoDot "Error when trying to connect to NoMachine server. Error is:"              "warn"
          printMsg      "$tmp"                                                                     "warn"
          printMsgNoDot "nxsetup cannot validate the sanity of the current installation:"          "warn"
          printMsg      "the current system or NoMachine configuration could be broken"            "warn"
          printMsgNoDot "If difficulties arise (for example sessions cannot be started),"          "warn"
          printMsgNoDot "it is advisable that you try to uninstall the NoMachine package and then" "warn"
          printMsgNoDot "install it again. Search also the NoMachine Knowledge Base at"            "warn"
          printMsgNoDot "https://www.nomachine.com/support"                                        "warn"
          printMsgNoDot "for common errors encountered when performing a software update"          "warn"
          printMsg      "and the related hints on how to solve them."                              "warn"

        else

          printMsgNoDot "Error when trying to connect to NoMachine server. Error is:"       "warn"
          printMsg      "$tmp"                                                              "warn"
          printMsg      "NoMachine server is stopped. Please start it: ${NXSHELL} --start"  "warn"

        fi
      else

        result=$(${ECHOCOMMAND} "${ret_getHello}" | ${GREPCOMMAND} -c "NX>" 2>&1)

        if [ $? != 0 ];
        then

          printMsgNoDot "Error when trying to connect to NoMachine server. Error is:" "warn"
          printMsg      "${ret_getHello}" "warn"
          printMsgNoDot "nxsetup cannot validate the sanity of the current installation:"          "warn"
          printMsg      "the current system or NoMachine configuration could be broken"            "warn"
          printMsgNoDot "If difficulties arise (for example sessions cannot be started),"          "warn"
          printMsgNoDot "it is advisable that you try to uninstall the NoMachine package and then" "warn"
          printMsgNoDot "install it again. Search also the NoMachine Knowledge Base at"            "warn"
          printMsgNoDot "https://www.nomachine.com/support"                                        "warn"
          printMsgNoDot "for common errors encountered when performing a software update"          "warn"
          printMsg      "and the related hints on how to solve them."                              "warn"

        fi
      fi
    fi

    if [ -f "${KEY_FILE_RSA}.prv" ];
    then
      commandRmIfExist "${KEY_FILE_RSA}.prv" "warn"
    fi

    if [ -f "${KEY_FILE_DSA}.prv" ];
    then
      commandRmIfExist "${KEY_FILE_DSA}.prv" "warn"
    fi
  fi
}

checkLastCommand ()
{
  #
  # 1 - LastCommand variable from runShCommand function.
  # 2 - message.
  # 3 - message type.
  #

  last_command="${1}"
  message="${2}"
  message_type="${3}"

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

    printMsg "${message}" "${message_type}"
    printMsg "${last_command}"

    if [ "x${stopped}" = "xyes" ];
    then

      startNXServer

      #
      # ret_checkLastCommand values:
      # 1 - end procedureServerKeygen function
      # 2 - end script (exit 1)
      #

      if [ ${ret_startNXServer} -eq 0 ];
      then
        ret_checkLastCommand=1
      else
        ret_checkLastCommand=2
      fi
    fi
  fi
}

checkExitCode ()
{
  #
  # 1 - LastCommand variable from runShCommand function.
  # 2 - message.
  # 3 - message type.
  #

  exit_code=${1}
  message="${2}"
  message_type="${3}"

  if [ ${exit_code} -ne 0 ]
  then

    printMsg "${message}" "${message_type}"

    if [ "x${stopped}" = "xyes" ];
    then

      startNXServer

      #
      # ret_checkExitCode values:
      # 1 - end procedureServerKeygen finction
      # 2 - end script (exit 1)
      #

      if [ ${ret_startNXServer} -eq 0 ];
      then
        ret_checkExitCode=1
      else
        ret_checkExitCode=2
      fi
    fi
  fi
}

removeUnusedAuthKeys ()
{
  #
  # 1 - key to remove.
  # 2 - key type (RSA/DSA).
  #

  remove_key="${1}"
  key_type="${2}"

  if [ -f "${remove_key}" ];
  then

    runShCommand "${RMCOMMAND} -f '${remove_key}'"

    checkLastCommand "${LastCommand}" "Cannot delete unused ${key_type} key" "error"

    ret_removeUnusedAuthKeys=${ret_checkLastCommand}

  fi
}

procedureServerKeygen ()
{

  #
  # Procedure moved to nxserver code.
  #

  newDSAKey="${NXHOME}/.ssh/new.id_dsa"
  newRSAKey="${NXHOME}/.ssh/new.id_rsa"

  if [ -f "${currentDSAKey}" ];
  then
    procedureRotateBackupAuthKey "${currentDSAKey}"
  fi

  if [ -f "${currentRSAKey}" ];
  then
    procedureRotateBackupAuthKey "${currentRSAKey}"
  fi

  if [ ! -f "${FILE_AUTHORIZED_KEYS}" ];
  then
    exit 1
  else
    stopped="yes"

    stopNXServer

    if [ ${ret_stopNXServer} != 0 ];
    then
      exit 1
    else

      printMsg "Starting: server-keygen operation at: ${currentTime}"

      #
      # Removing leftovers
      #

      ret_removeUnusedAuthKeys=0

      removeUnusedAuthKeys "${newDSAKey}" DSA

      if [ ${ret_removeUnusedAuthKeys} -eq 0 ]
      then
        removeUnusedAuthKeys "${newDSAKey}.pub" DSA
      fi
      if [ ${ret_removeUnusedAuthKeys} -eq 0 ]
      then
        removeUnusedAuthKeys "${newRSAKey}" RSA
      fi
      if [ ${ret_removeUnusedAuthKeys} -eq 0 ]
      then
        removeUnusedAuthKeys "${newRSAKey}.pub" RSA
      fi

      if [ ${ret_removeUnusedAuthKeys} -eq 1 ]
      then
        return 0
      elif [ ${ret_removeUnusedAuthKeys} -eq 2 ]
      then
        exit 1
      elif [ ${ret_removeUnusedAuthKeys} -eq 0 ]
      then

        printMsg "Generating new SSH keys"

        ret_checkLastCommand=0

        if [ ${SELINUX_ENABLED} = 1 ];
        then

          runShCommand "NX_SYSTEM='${NX_ROOT}'\
                           LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH' ${RUNCONCOMMAND} -u root -r system_r -t initrc_t\
                                --${NXKEYGENCOMMAND} -k '${newDSAKey}' -p '${newDSAKey}.pub' -t dsa"

          checkLastCommand "${LastCommand}" "Cannot generate DSA keys for NoMachine Server authentication" "error"

          if [ ${ret_checkLastCommand} -eq 0 ]
          then
            runShCommand "NX_SYSTEM='${NX_ROOT}'\
                             LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH' ${RUNCONCOMMAND} -u root -r system_r -t initrc_t\
                                 --${NXKEYGENCOMMAND} -k '${newRSAKey}' -p '${newRSAKey}.pub'"

            checkLastCommand "${LastCommand}" "Cannot generate RSA keys for NoMachine Server authentication" "error"

            commandChown "${USER_NX}" "${newRSAKey}"
            commandChown "${USER_NX}" "${newRSAKey}.pub"

            commandChown "${USER_NX}" "${newDSAKey}"
            commandChown "${USER_NX}" "${newDSAKey}.pub"
          fi
        else
          runShCommand "NX_SYSTEM='${NX_ROOT}'\
                           LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH'\
                               ${NXKEYGENCOMMAND} -k '${newDSAKey}' -p '${newDSAKey}.pub' -t dsa"

          checkLastCommand "${LastCommand}" "Cannot generate DSA keys for NoMachine Server authentication" "error"

          if [ ${ret_checkLastCommand} -eq 0 ]
          then
            runShCommand "NX_SYSTEM="${NX_ROOT}"\
                             LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH'\
                                 ${NXKEYGENCOMMAND} -k '${newRSAKey}' -p '${newRSAKey}.pub'"

            checkLastCommand "${LastCommand}" "Cannot generate RSA keys for NoMachine Server authentication" "error"
          fi
        fi

        if [ ${ret_removeUnusedAuthKeys} -eq 1 ]
        then
          return 0
        elif [ ${ret_removeUnusedAuthKeys} -eq 2 ]
        then
          exit 1
        elif [ ${ret_removeUnusedAuthKeys} -eq 0 ]
        then

          ret_checkExitCode=0

          out=$(${BASHSHELL} -c "${ECHOCOMMAND} -n 'no-port-forwarding,no-agent-forwarding,command=\"${NXSHELL} --login\" ' > '${NXHOME}/.ssh/tmp.id_rsa' 2>&1")

          checkExitCode "$?" "Cannot create RSA keys for NoMachine Server authentication" "error"

          if [ ${ret_checkExitCode} -eq 0 ]
          then
            out=$(${BASHSHELL} -c "${ECHOCOMMAND} -n 'no-port-forwarding,no-agent-forwarding,command=\"${NXSHELL} --login\" ' > '${NXHOME}/.ssh/tmp.id_dsa' 2>&1")

            checkExitCode "$?" "Cannot create DSA keys for NoMachine Server authentication" "error"
          fi

          if [ ${ret_checkExitCode} -eq 1 ]
          then
            return 0
          elif [ ${ret_checkExitCode} -eq 2 ]
          then
            exit 1
          elif [ ${ret_checkExitCode} -eq 0 ]
          then

            ret_checkLastCommand=0

            runShCommand "${CATCOMMAND} '${newDSAKey}.pub' >> '${NXHOME}/.ssh/tmp.id_dsa'"

            checkLastCommand "${LastCommand}" "Cannot create DSA key for NoMachine Server authentication" "error"

            if [ ${ret_checkLastCommand} -eq 0 ]
            then
              runShCommand "${CATCOMMAND} '${newRSAKey}.pub' >> '${NXHOME}/.ssh/tmp.id_rsa'"

              checkLastCommand "${LastCommand}" "Cannot create RSA key for NoMachine Server authentication" "error"
            fi

            if [ ${ret_checkExitCode} -eq 1 ]
            then
              commandRm "${NXHOME}/.ssh/tmp.id_dsa" "warn"
              commandRm "${NXHOME}/.ssh/tmp.id_rsa" "warn"

              return 0
            elif [ ${ret_checkExitCode} -eq 2 ]
            then
              commandRm "${NXHOME}/.ssh/tmp.id_dsa" "warn"
              commandRm "${NXHOME}/.ssh/tmp.id_rsa" "warn"

              exit 1
            elif [ ${ret_checkExitCode} -eq 0 ]
            then

              commandRm "${newRSAKey}.pub" "warn"
              commandRm "${newDSAKey}.pub" "warn"

              #
              # Backup old id_rsa and id_dsa keys.
              #

              printMsg "Keys generated correctly. Backing up files"

              if [ -f "${NX_ROOT}/share/keys/default.id_rsa.key" ];
              then
                commandBackupFile "${NX_ROOT}/share/keys/default.id_rsa.key" "backup" "warn"
              fi

              if [ -f "${NX_ROOT}/share/keys/server.id_rsa.key" ];
              then
                commandBackupFile "${NX_ROOT}/share/keys/server.id_rsa.key" "backup" "warn"
              fi

              if [ -f "${NX_ROOT}/share/keys/default.id_dsa.key" ];
              then
                commandBackupFile "${NX_ROOT}/share/keys/default.id_dsa.key" "backup" "warn"
              fi

              if [ -f "${NX_ROOT}/share/keys/server.id_dsa.key" ];
              then
                commandBackupFile "${NX_ROOT}/share/keys/server.id_dsa.key" "backup" "warn"
              fi

              commandCp "${NX_ROOT}/share/keys/default.id_rsa.key" "${NX_ROOT}/share/keys/server.id_rsa.key" "warn"
              commandCp "${NX_ROOT}/share/keys/default.id_dsa.key" "${NX_ROOT}/share/keys/server.id_dsa.key" "warn"

              printMsg "Back up of keys made. Updating files"

              commandMv "${NXHOME}/.ssh/tmp.id_rsa" "${currentRSAKey}" "warn"
              commandMv "${NXHOME}/.ssh/tmp.id_dsa" "${currentDSAKey}" "warn"

              runShCommand "NX_SYSTEM="${NX_ROOT}"\
                               LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH'\
                                   ${NXKEYGENCOMMAND} -y '${NX_ROOT}/share/keys/server.id_dsa.key'"

              runShCommand "NX_SYSTEM="${NX_ROOT}"\
                               LD_LIBRARY_PATH='${NX_ROOT}/lib:$LD_LIBRARY_PATH'\
                                   ${NXKEYGENCOMMAND} -y '${NX_ROOT}/share/keys/server.id_rsa.key'"

              if [ -f "${NXHOME}/.ssh/authorized_keys2" ];
              then

                commandBackupFile "${NXHOME}/.ssh/authorized_keys2" "backup" "warn"

                "${SEDCOMMAND}" '/nxserver.*'"${oldPubCommand}"'/d' "${NXHOME}/.ssh/authorized_keys2" > "${NXHOME}/.ssh/authorized_keys2.tmp"

                commandRestoreFile "${NXHOME}/.ssh/authorized_keys2" "tmp"

                "${CATCOMMAND}" "${currentRSAKey}" >> "${NXHOME}/.ssh/authorized_keys2"
                "${CATCOMMAND}" "${currentDSAKey}" >> "${NXHOME}/.ssh/authorized_keys2"
              fi

              if [ -f "${NXHOME}/.ssh/authorized_keys" ];
              then

                commandBackupFile "${NXHOME}/.ssh/authorized_keys" "backup" "warn"

                "${SEDCOMMAND}" '/nxserver.*'"${oldPubCommand}"'/d' "${NXHOME}/.ssh/authorized_keys" > "${NXHOME}/.ssh/authorized_keys.tmp"

                commandRestoreFile "${NXHOME}/.ssh/authorized_keys" "tmp"

                "${CATCOMMAND}" "${currentRSAKey}" >> "${NXHOME}/.ssh/authorized_keys2"
                "${CATCOMMAND}" "${currentDSAKey}" >> "${NXHOME}/.ssh/authorized_keys2"
              fi

              commandMv "${newRSAKey}" "${NX_ROOT}/share/keys/default.id_rsa.key" "warn"
              commandMv "${newDSAKey}" "${NX_ROOT}/share/keys/default.id_dsa.key" "warn"

              commandChmod "0600" "${NX_ROOT}/share/keys/default.id_rsa.key" "warn"
              commandChmod "0600" "${NX_ROOT}/share/keys/default.id_dsa.key" "warn"

              commandCp "${NX_ROOT}/share/keys/default.id_rsa.key" "${NX_ROOT}/share/keys/server.id_rsa.key" "warn"
              commandCp "${NX_ROOT}/share/keys/default.id_dsa.key" "${NX_ROOT}/share/keys/server.id_dsa.key" "warn"

              commandChown "${USER_NX}:${ROOTGNAME}" "${currentRSAKey}" "warn"
              commandChown "${USER_NX}:${ROOTGNAME}" "${currentDSAKey}" "warn"

              setContextForAuthKeys

              FILE_AUTHORIZED_KEYS_ENABLED=0

              getNodeConfigFile

              if [ "x${stopped}" = "xyes" ];
              then

                startNXServer

                if [ ${ret_startNXServer} = 0 ];
                then

                  setAuthorizedKeyFileName

                  printMsgNoDot "Keys updated. NoMachine clients should now use key:"
                  printMsgNoDot "${NX_ROOT}/share/keys/default.id_rsa.key"
                  printMsgNoDot "${NX_ROOT}/share/keys/default.id_dsa.key"
                  printMsg "to get connected to this NoMachine server"

                else
                  return 0
                fi
              fi
            fi
          fi
        fi
      fi
    fi
  fi
}

getNodeConfigFile ()
{
  NODE_CONFIG_FILE="${NX_ROOT}/etc/node.cfg"
}

setAvailableSessionKey ()
{
  getNodeConfigFile

  getValueFromCfgFile "AvailableSessionTypes" "${NODE_CONFIG_FILE}"
  updateAvailableSessionKey "${cfg_val}" "${CONFIG_FILE}"
}

updatePathinAuthKey ()
{
  #
  # Old updatePathinDSAKey function.
  # 1 - Key path
  #

  AuthKeyPath="${1}"

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

    #
    # FIXME: update regexp to manage paths on Mac OS X
    #

    printMsg "Skipping updating NXSHELL in file: ${AuthKeyPath}" "onlylog"

    return 0
  fi

  #
  # Updating the path for NXSHELL inside ${AuthKeyPath}
  #

  out_grep=$(${GREPCOMMAND} "command=\"${NXSHELL} --login\"" ${AuthKeyPath} 2>&1)

  if [ "x${out_grep}" = "x" ];
  then
    printMsg "Updating NXSHELL in file: ${AuthKeyPath}" "cmd"

    ${SEDCOMMAND} -e 's:command=\".*--login\":command=\"'"${NXSHELL}"' --login\":' "${AuthKeyPath}" > "${AuthKeyPath}.tmp"
    commandRestoreFile "${AuthKeyPath}" "tmp"

    out_grep=$(${GREPCOMMAND} "command=\"${NXSHELL} --login\"" "${AuthKeyPath}" 2>&1)

    if [ "x${out_grep}" = "x" ];
    then
      printMsg "Error while updating NXSHELL in file: '${AuthKeyPath}" "cmd"
    fi
  fi
}

setPhysicalDesktopSharing ()
{
  getLicenseAcronym

  if [ "x${LICENSE_ACRONYM:1:2}" != "xED" ] && [ "x${LICENSE_ACRONYM:1:1}" != "xS" ] && \
     [ "x${LICENSE_ACRONYM:1:2}" != "xTE" ];
  then
    getValueFromCfgFile "PhysicalDesktopSharing" "$CONFIG_FILE"

    if [ "x$ret_getValueFromCfgFile" = "x1" ] && [ "x$cfg_val" = "x1" ];
    then
      setValueAtCfgFile "$CONFIG_FILE" "#PhysicalDesktopSharing" "2"
    fi
  fi
}

updateDesktopSharingKeys ()
{
  renameKey "PhysicalDesktopAuthorization" "VirtualDesktopAuthorization"
  removeOptionFromCfgNew "VirtualDesktopAuthorization" "Enable, disable or restrict NX Server requesting authorization to"
  removeOptionFromCfgNew "VirtualDesktopSharing" "Allow the user to connect to a virtual desktop:"
  removeOptionFromCfgNew "PhysicalDesktopSharing" "Allow the user to connect to the physical desktop:"

  insertKeytoConfigFile "PhysicalDesktopAccess" "\n\
#\n\
# Allow the given type of users to connect to the physical desktop.\n\
# Set this key to 'all' to allow all kind of users, or to 'none' to\n\
# completely forbid access to the physical desktop. Otherwise give\n\
# a comma-separated list of values to indicate which type of users\n\
# is allowed to connect, order is not relevant. Accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users for connections to physical\n\
#                desktop.\n\
#\n\
# system:        all unprivileged users who have a valid account to\n\
#                login.\n\
#\n\
# guest:         Guest Desktop Sharing users. Guests are not allowed\n\
#                to connect to the desktop of a cloud server.\n\
#\n\
# owner:         the owner of the remote desktop.\n\
#\n\
#PhysicalDesktopAccess administrator,trusted,system,guest,owner" "VirtualDesktopMode"

  insertKeytoConfigFile "PhysicalDesktopAccessNoAcceptance" "\n\
#\n\
# When allowed to connect to the physical desktop, specify which\n\
# kind of users don't need the authorization of the desktop owner.\n\
# Set this key to 'all' to allow all kind of users except the guest\n\
# desktop sharing users who always require the owner's approval.\n\
# Set it to 'none' to always require the owner's approval or provide\n\
# a comma-separated list of type of users, order is not relevant.\n\
# Accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users for connections to physical\n\
#                desktop.\n\
#\n\
# system:        all unprivileged users who have a valid account to\n\
#                login.\n\
#\n\
# owner:         the owner of the remote desktop.\n\
#\n\
#PhysicalDesktopAccessNoAcceptance administrator,trusted,system,owner,system" "PhysicalDesktopMode"

  insertKeytoConfigFile "ScreenSharingOwnerAccess" "\n\
#\n\
# Enable or disable the desktop owner to access the remote physical\n\
# desktop if screen sharing is disabled.\n\
#\n\
# 1: Enabled. The desktop owner can always connect, also when screen\n\
#    sharing is disabled. This is default.\n\
#\n\
# 0: Disabled. The desktop owner cannot connect when screen sharing\n\
#    is disabled.\n\
#\n\
#ScreenSharingOwnerAccess 1" "PhysicalDesktopAccessNoAcceptance"

  insertKeytoConfigFile "EnableScreenSharingMode" "\n\
#\n\
# Configure automatically NoMachine for allowing only connections\n\
# to the remote physical display upon desktop owner's authorization.\n\
# This overrides more permissive settings set in LoginScreenAccess,\n\
# ScreenSharingOwnerAccess and PhysicalDesktopAccessNoAcceptance.\n\
#\n\
# 1: Enabled. All connections must be explicitly accepted to be\n\
#    allowed to proceed. Use this setting only if the computer is\n\
#    running attended.\n\
#\n\
# 0: Disabled. Desktop owner's authorization is requested according\n\
#    to values set in keys PhysicalDesktopAccessNoAcceptance and\n\
#    ScreenSharingOwnerAccess. Access to login screen depends on\n\
#    value set for LoginScreenAccess.\n\
#\n\
#EnableScreenSharingMode 0" "ScreenSharingOwnerAccess"

  if [ "x${LICENSE_ACRONYM:1:2}" = "xED" ] && [ "x${LICENSE_ACRONYM:1:1}" = "xS" ] && \
     [ "x${LICENSE_ACRONYM:1:2}" = "xTE" ];
  then
    removeOptionFromCfgNew "VirtualDesktopAccess" "Allow the given type of users to connect to a virtual desktop."
    removeOptionFromCfgNew "VirtualDesktopAccessNoAcceptance" "When allowed to connect to a virtual desktop, specify which kind"
  else
    insertKeytoConfigFile "VirtualDesktopAccess" "\n\
#\n\
# Allow the given type of users to connect to a virtual desktop.\n\
# Set this key to 'all' to allow all kind of users, or to 'none' to\n\
# completely forbid connections to already running virtual desktops.\n\
# Otherwise give a comma-separated list of values to indicate which\n\
# type of users is allowed to connect, order is not relevant and\n\
# accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users for connections to physical\n\
#                desktop.\n\
#\n\
# system:        all unprivileged users who have a valid account to\n\
#                login.\n\
#\n\
# guest:         Guest Desktop Sharing users\n\
#\n\
# owner:         the owner of the remote desktop.\n\
#\n\
#VirtualDesktopAccess administrator,trusted,owner,system" "UserHome"

    insertKeytoConfigFile "VirtualDesktopAccessNoAcceptance" "\n\
#\n\
# When allowed to connect to a virtual desktop, specify which kind\n\
# of users don't need the authorization of the virtual desktop owner.\n\
# Set this key to 'all' to allow all kind of users except the guest\n\
# desktop sharing users who always require the owner's approval.\n\
# Set it to 'none' to require every time the owner's approval or provide\n\
# a comma-separated list of type of users, order is not relevant.\n\
# Accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users for connections to physical\n\
#                desktop.\n\
#\n\
# system:        all unprivileged users who have a valid account to\n\
#                login.\n\
#\n\
# owner:         the owner of the remote desktop.\n\
#\n\
#VirtualDesktopAccessNoAcceptance administrator,trusted,owner" "VirtualDesktopMode"

  fi
}

updateConfigFile ()
{
  #
  # Updating localhost/server.cfg.
  #

  os_name="Linux"

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

  server_localhost="/etc/NX/server/localhost/server.cfg"
  node_localhost="/etc/NX/node/localhost/server.cfg"

  if ([ "x${PACKAGE_NAME}" = "xserver" ] || [ "x${PACKAGE_NAME}" = "xnode" ]) && \
      [ "x${UPDATETYPE}" = "xauto" ]
  then

    insertKeytoConfigFile "NXUserHome" "\n\
#\n\
# Specify the path of the home directory of the nx user on ${os_name}.\n\
#\n\
NXUserHome = \\\"${NXUSERHOME}/nx/.nx\\\"" "ServerRoot" "${server_localhost}"

    insertKeytoConfigFile "NXUserHome" "\n\
#\n\
# Specify the path of the home directory of the nx user on ${os_name}.\n\
#\n\
NXUserHome = \\\"${NXUSERHOME}/nx/.nx\\\"" "ServerRoot" "${node_localhost}"

  elif ([ "x${PACKAGE_NAME}" = "xserver" ] || [ "x${PACKAGE_NAME}" = "xnode" ]) && \
        [ "x${UPDATETYPE}" != "xauto" ]
  then
    ${SEDCOMMAND} -e 's/# Specify the path of the home directory of the nx user on Windows/# Specify the path of the home directory of the nx user on '"${os_name}"'/g' "${server_localhost}" > "${server_localhost}.tmp"
    commandRestoreFile "${server_localhost}" "tmp"
  fi

  #
  # Updating NX/etc/ config files.
  #

  insertKeytoConfigFile "EnableUPnPSession" "\n\
#\n\
# Enable UPnP support in the session to map the port on the gateway\n\
# for UDP communication when the NX protocol is used. This requires\n\
# that the EnableUPnP key includes the 'NX' value. Accepted values\n\
# are:\n\
#\n\
# 1: Enabled. Use UPnP to map the UDP port for the session.\n\
#\n\
# 0: Disabled. Do not use UPnP to map the UDP port.\n\
#\n\
#EnableUPnPSession 0" "EnableUPnP"

  insertKeytoConfigFile "NXUDPUPnPPort" "\n\
#\n\
# Specify the port where the NX service will be redirected using NAT-\n\
# PMP or UPnP to allow end-users to connect to the server through a\n\
# firewall.\n\
#\n\
#NXUDPUPnPPort\\\"\\\"" "EnableUPnPSession"

  insertKeytoConfigFile "HTTPUPnPPort" "\n\
#\n\
# Specify the port where the HTTP service will be redirected using\n\
# NAT-PMP or UPnP to allow end-users to connect to the server through\n\
# a firewall.\n\
# \n\
#HTTPUPnPPort \\\"\\\"" "SSHUPnPPort"

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

  insertKeytoConfigFile "EnableNetworkBroadcast" "\n\
#\n\
# Enable or disable broadcasting the required information to let\n\
# other computers discover this host on the local network.\n\
#\n\
# 1: Enabled. Other computers on the local network can find\n\
#    this host machine.\n\
#\n\
# 0: Disabled. This computer cannot be found on the local\n\
#    network but it's still reachable by providing its IP\n\
#    or hostname.\n\
#\n\
#EnableNetworkBroadcast 1" "SSHClient"

  insertKeytoConfigFile "RunNodeMode" "\n\
#\n\
# Specify how the node process is run.\n\
#\n\
# 1: Noshell. Execute script to run the node process directly.\n\
#\n\
# 0: Shellmode. Execute script to run the node process by\n\
#    invoking the bash shell.\n\
#\n\
#RunNodeMode 0" "ConnectPolicy"

  insertKeytoConfigFile "EnableFirewallConfiguration" "\n\
#\n\
# Enable the server to automatically configure the firewall for all\n\
# the configured services. On platforms that don't support adding\n\
# the specific executables to a white list, the needed ports are\n\
# added at server startup and removed at server shutdown, or when,\n\
# at run-time, a new port is needed. The default value is 1.\n\
#\n\
# 1: Enabled. NoMachine opens the required ports in the firewall.\n\
#\n\
# 0: Disabled. Firewall must be configured manually. By default\n\
#    the required ports are TCP ports 4000 for NX, 4080 and 4443\n\
#    for HTTP and UDP ports in the range 4011-4999 range.\n\
#\n\
#EnableFirewallConfiguration 1" "RunNodeMode"

  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 server will log to the system log file.\n\
#\n\
# 0: Disabled. This is the default value, the server will log to\n\
#    the file specified in the SystemLogFile key.\n\
#\n\
#EnableSyslogSupport 0" "EnableFirewallConfiguration"

  ${SEDCOMMAND} -e 's/# Enable or disable syslog. NX Server 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 server 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./' \
                "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  #
  # Change key names.
  #

  command="${GREPCOMMAND} 'EnableHttpDaemon' '${CONFIG_FILE}'"

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

  if [ $? = 0 ];
  then
    ${SEDCOMMAND} -e 's/EnableHttpDaemon /StartHTTPDaemon /' -e 's/Enabled. Enable starting of the http server/Automatic. Enable automatic starting of the HTTP server/' \
-e 's/Disabled. Disable starting of the http server./Manual. Disable automatic starting of the HTTP server.\
#    The server can be started manually./' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

    ${SEDCOMMAND} -e 's/StartHTTPDaemon *1/StartHTTPDaemon Automatic/' -e 's/StartHTTPDaemon *0/StartHTTPDaemon Manual/' "${CONFIG_FILE}.tmp" > "${CONFIG_FILE}"
  fi

  insertKeytoConfigFile "StartNXDaemon" "\n\
#\n\
# Enable or disable starting the NX service. If enabled, the service\n\
# will be started automatically at every reboot.\n\
#\n\
# 1: Automatic. Enable automatic starting of the NX server.\n\
#\n\
# 0: Manual. Disable automatic starting of the NX server.\n\
#    The server can be started manually.\n\
#\n\
#StartNXDaemon Automatic" "StartHTTPDaemon"

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

  insertKeytoConfigFile "DisconnectedSessionExpiry" "\n\
#\n\
# Set for how long the server has to keep alive virtual desktops in\n\
# status disconnected. When the time is expired, the server will\n\
# terminate virtual desktops if no user are connected there.\n\
#\n\
#  0: Virtual desktops in status disconnected are never terminated.\n\
#     This is the default.\n\
#\n\
# >0: Keep alive virtual desktops in status disconnected for this\n\
#     amount of seconds.\n\
#\n\
#DisconnectedSessionExpiry 0" "EnableSyslogSupport"

  fi

  insertKeytoConfigFile "AuthorizationTimeout" "\n\
#\n\
# Set for how long the server will wait for the authentication phase\n\
# to be completed on the system. By default timeout is set to 30\n\
# seconds. Increase this value when the authentication process on\n\
# the system takes longer. This setting applies also to two-factor\n\
# authentication.\n\
#\n\
#AuthorizationTimeout 30" "NetLogonDependency"

  insertKeytoConfigFile "CreateDisplay" "\n\
#\n\
# Enable or disable the automatic creation of an X11 display when no\n\
# X servers are running on this host (e.g. headless machine) to let\n\
# users connect to the desktop. This setting applies to NoMachine\n\
# servers not supporting virtual desktops and permits to have one\n\
# single display.\n\
#\n\
# 1: Enabled. NoMachine will create automatically the new display at\n\
#    server startup. This setting has to be used in conjunction with\n\
#    'DisplayOwner' and 'DisplayGeometry'.\n\
#\n\
# 0: Disabled. NoMachine will prompt the user for creating the new\n\
#    display. This is the default.\n\
#\n\
#CreateDisplay 0" "EnableNetwork"

  "${AWKCOMMAND}" '/^.*DisplayOwner.*and.*DisplayGeometry/{p=1;print;print "#\n# 0: Disabled. NoMachine will prompt the user for creating the new\n#    display. This is the default.\n#"}/CreateDisplay/{p=0}!p' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  insertKeytoConfigFile "DisplayOwner" "\n\
#\n\
# When 'CreateDisplay' is enabled, specify the display owner and let\n\
# NoMachine create the new display without querying the user. If the\n\
# server supports only one concurrent connection, the connecting user\n\
# must be the display owner set in this key.\n\
#\n\
#DisplayOwner \\\"\\\"" "CreateDisplay"

  insertKeytoConfigFile "DisplayGeometry" "\n\
#\n\
# When 'CreateDisplay' is enabled, specify the resolution of the new\n\
# desktop in the WxH format. Default is 800x600.\n\
#\n\
#DisplayGeometry 800x600" "DisplayOwner"

  insertKeytoConfigFile "EnableNXKerberosAuthentication" "\n\
#\n\
# Enable or disable support for Kerberos ticket-based authentication\n\
# for connections by NX protocol.\n\
#\n\
# 1: Enabled. Kerberos ticket-based authentication is supported when\n\
#    users connect by the NX protocol.\n\
#\n\
# 0: Disabled. Kerberos ticket-based authentication is not supported\n\
#    for connections by NX protocol. This is the default.\n\
#\n\
#EnableNXKerberosAuthentication 0" "DisplayGeometry"

  insertKeytoConfigFile "NXKerberosAuthenticationTimeout" "\n\
#\n\
# Set for how long the server will wait for the kerberos response\n\
# from kerberos kdc server. By default timeout is set to 10 seconds.\n\
# Increase this value when the authentication process on the system\n\
# takes longer.\n\
#\n\
#NXKerberosAuthenticationTimeout 10" "EnableNXKerberosAuthentication"

  insertKeytoConfigFile "NXKerberosRequestLimit" "\n\
#\n\
# Set the maximum size for the Kerberos authentication request, by\n\
# default 1048576 bytes.\n\
#\n\
#NXKerberosRequestLimit 1048576" "NXKerberosAuthenticationTimeout"

  insertKeytoConfigFile "EnableNXKerberosForwardingToRemote" "\n\
#\n\
# Enable or disable support for Kerberos ticket forwarding to the\n\
# remote node when the user didn't authenticate with Kerberos, but\n\
# their Kerberos ticket is already available on the server system.\n\
# This key applies to a multi-node environment only and it's di-\n\
# sabled by default.\n\
#\n\
# 1: Enabled. User's Kerberos ticket already available on the\n\
#    NoMachine server system will be forwarded to the remote node\n\
#    where the user's session is started.\n\
#\n\
# 0: Disabled. User's Kerberos ticket will not be forwarded to the\n\
#    remote node where the user's session is started.\n\
#\n\
#EnableNXKerberosForwardingToRemote 0" "NXKerberosRequestLimit"

  insertKeytoConfigFile "NXGssapiLibraryPath" "\n\
#\n\
# Specify path to the GSSAPI library to be used for authentication.\n\
#\n\
#NXGssapiLibraryPath \\\"\\\"" "EnableNXKerberosForwardingToRemote"

  insertKeytoConfigFile "NXKerberosLibraryPath" "\n\
#\n\
# Specify path to the Kerberos library module to be used for user's\n\
# authentication.\n\
#\n\
#NXKerberosLibraryPath \\\"\\\"" "NXGssapiLibraryPath"

  insertKeytoConfigFile "AcceptedAuthenticationMethods" "\n\
#\n\
# Specify how clients will have to authenticate to the server, by\n\
# default all the available methods are supported. This corresponds\n\
# to value all. To specify a subset of methods use a comma-separated\n\
# list.\n\
#\n\
# Supported methods for connections by NX protocol are:\n\
# NX-password   : Password authentication.\n\
# NX-private-key: Key-based authentication.\n\
# NX-kerberos   : Kerberos ticket-based authentication.\n\
#\n\
# Supported method for connections by SSH protocol is:\n\
# SSH-system    : All methods supported for the system login.\n\
#                SSH authentication methods for the system login\n\
#                have to be set on the system for example in the\n\
#                PAM configuration.\n\
#\n\
#AcceptedAuthenticationMethodsPARTTWO\n\
#AcceptedAuthenticationMethods all" "NXGssapiLibraryPath"

  ${SEDCOMMAND} 's/#AcceptedAuthenticationMethodsPARTTWO/# For example:\n# AcceptedAuthenticationMethods NX-private-key,SSH-system\n#\n# This key has to be used in conjunction with ClientConnectionMethod.\n# See also the EnableNXClientAuthentication key for enabling SSL\n# client authentication for connections by NX protocol.\n#/g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  insertKeytoConfigFile "EnableNXClientAuthentication" "\n\
#\n\
# Enable or disable support for SSL client authentication in the NX\n\
# service.\n\
#\n\
# 1: Enabled. The NX service, nxd, uses the client side certificate\n\
#    to validate the connecting client against a list of allowed\n\
#    clients. Only clients owning a certificate valid for this NX\n\
#    service can authenticate with this method.\n\
#\n\
# 0: Disabled. Authentication by using a client side certificate\n\
#    is not possible.\n\
#\n\
# This option applies to connections by NX protocol only and it's\n\
# disabled by default.\n\
#\n\
#EnableNXClientAuthentication 0" "NXGssapiLibraryPath"

  insertKeytoConfigFile "EnableClientCredentialsStoring" "\n\
#\n\
# Enable or disable users to store their access credentials on their\n\
# devices when they connect via NoMachine client or in the browser's\n\
# cookie in case of web sessions.  Accepted values are:\n\
#\n\
# player:    Allow only users connected via NoMachine client to save\n\
#            username and password in their connection file.\n\
#\n\
# webplayer: Allow only users connected via web to store username and\n\
#            password in the browser's cookies, if enabled.\n\
#\n\
# both:      Users connected via client or via web can always choose to\n\
#            store their credentials.\n\
#\n\
# none:      Do not permit users to save their username and password.\n\
#            Users will be requested to insert their credentials at\n\
#            each new connection via NoMachine client or web.\n\
#\n\
EnableClientCredentialsStoring both" "ClientMenuConfiguration"

  insertKeytoConfigFile "NXGSSAPIStrictAcceptorCheck" "\n\
#\n\
# Enable or disable strict GSSAPI host credential check for Kerberos\n\
# authentication. When enabled, authentication is done against the\n\
# host service on the current hostname. If disabled, authentication\n\
# is done against any requested service key stored in the keytab file.\n\
#\n\
# 1: Enabled. Kerberos authentication is made strictly against hostname\n\
#    host service. This is the default.\n\
#\n\
# 0: Disabled. Allow relaxed GSSAPI host credential check, and make\n\
#    possible to authenticate against GSSAPI host service with a\n\
#    different name than hostname.\n\
#\n\
#NXGSSAPIStrictAcceptorCheck 1" "EnableClientCredentialsStoring"

  insertKeytoConfigFile "EnableDirectConnections" "\n\
#\n\
# Enable or disable this server accepting direct connections to its\n\
# IP or hostname when it's federated in a multi-server environment.\n\
#\n\
# 1: Enabled. Users are allowed to connect to this NoMachine server.\n\
#\n\
# 0: Disabled. Users have to connect to the main server ruling the\n\
# multi-host environment in order to reach this server.\n\
#\n\
#EnableDirectConnections 1" "NXGSSAPIStrictAcceptorCheck"

  insertKeytoConfigFile "EnableSystemGroupsForwardingToRemote" "\n\
#\n\
# Enable or disable forwarding system groups to the remote node. This\n\
# key applies to a multi-node environment only and it's disabled by\n\
# default.\n\
#\n\
# 1: Enabled. On the remote node, users will be part of a system\n\
#    group configured on the main server host.\n\
#\n\
# 0: Disabled. System groups configured on the main server host\n\
#    are not forwarded to the nodes.\n\
#\n\
#EnableSystemGroupsForwardingToRemote 0" "EnableDirectConnections"

  insertKeytoConfigFile "NetworkHostName" "\n\
#\n\
# Specify the name for identifying this computer on the network.\n\
#\n\
#NetworkHostName \\\"\\\"" "EnableNetwork"

  insertKeytoConfigFile "NetworkOnlyMode" "\n\
#\n\
# Enable or disable handling incoming connections only from\n\
# NoMachine Network.\n\
#\n\
# 1: Enabled. Only handle connections from NoMachine Network.\n\
#\n\
# 0: Disabled. Handle connections from Network and direct over IP (default).\n\
#\n\
#NetworkOnlyMode 0" "NetworkHostName"

  insertKeytoConfigFile "EnableNetwork" "\n\
#\n\
# Allow or block the NoMachine Network functionality.\n\
#\n\
# 1: Enabled. This server can join the NoMachine Network service.\n\
#\n\
# 0: Disabled. Computer publishing and desktop sharing via NoMachine\n\
#    Network are disabled for this server. All related key settings\n\
#    are ignored. Users can still connect to this server by IP and\n\
#    port.\n\
#\n\
#EnableNetwork 1" "NetworkOnlyMode"

  insertKeytoConfigFile "WebSessionLanguage" "\n\
#\n\
# Specify the GUI language. Available languages are: English (default)\n\
# French, German, Italian, Spanish, Polish, Portuguese and Russian.\n\
# Users will be still able to change the language in the GUI.\n\
#\n\
#WebSessionLanguage English"  "EnableNetwork"

  insertKeytoConfigFile "WebSessionTheme" "\n\
#\n\
# Specify the GUI theme, sunshine (default) or moonlight. Users will\n\
# be still able to change GUI theme in the GUI.\n\
#\n\
#WebSessionTheme sunshine" "WebSessionLanguage"

  insertKeytoConfigFile "WebSessionWave" "\n\
#\n\
# Specify the wave theme, red (default), light gray or dark gray.\n\
# Users will be still able to change wave theme in the GUI.\n\
#\n\
#WebSessionWave red" "WebSessionTheme"

  insertKeytoConfigFile "ScriptBeforeServerDaemonStart" "\n\
#\n\
# Specify absolute path of the script to be executed before\n\
# the server daemon is started.\n\
#\n\
#ScriptBeforeServerDaemonStart \\\"\\\"" "UserScriptAfterEnableUser"

  insertKeytoConfigFile "ScriptAfterServerDaemonStart" "\n\
#\n\
# Specify absolute path of the script to be executed after\n\
# the server daemon is started.\n\
#\n\
#ScriptAfterServerDaemonStart \\\"\\\"" "ScriptBeforeServerDaemonStart"

  insertKeytoConfigFile "ScriptBeforeServerDaemonStop" "\n\
#\n\
# Specify absolute path of the script to be executed before\n\
# the server daemon is stopped.\n\
#\n\
#ScriptBeforeServerDaemonStop \\\"\\\"" "ScriptAfterServerDaemonStart"

  insertKeytoConfigFile "ScriptAfterServerDaemonStop" "\n\
#\n\
# Specify absolute path of the script to be executed after\n\
# the server daemon is stopped.\n\
#\n\
#ScriptAfterServerDaemonStop \\\"\\\"" "ScriptBeforeServerDaemonStop"

  insertKeytoConfigFile "CustomErrorMessages" "\n\
#\n\
# Specify path and name to the script to be executed for displaying\n\
# a custom message to users in addition to the default error message.\n\
# To create your own script, use the nxcustomerrormessages template\n\
# stored in scripts/env under the NoMachine installation directory.\n\
#\n\
#CustomErrorMessages \\\"\\\"" "ScriptAfterServerDaemonStop"

  insertKeytoConfigFile "EnableDebug" "\n\
#\n\
# Enable or disable the debug tool when the server program is launched.\n\
#\n\
# 1: Enabled. The debug tool specified in the CommandDebug key will\n\
#    be run to debug the server program. This can slow down the exe-\n\
#    cution of the server.\n\
#\n\
# 0: Disabled. Debug tool is not run.\n\
#\n\
#EnableDebug 0" "ScriptAfterServerDaemonStop"

  insertKeytoConfigFile "CommandDebug" "\n\
#\n\
# Specify absolute path of the command to launch a debug tool.\n\
#\n\
#CommandDebug \\\"\\\"" "EnableDebug"

  insertKeytoConfigFile "AcceptedDebuggerCommands" "\n\
#\n\
# Specify path and commands of the debug tool in a comma-separated\n\
# list, e.g. accepted command for Valgrind is '/usr/bin/valgrind.bin'.\n\
#\n\
#AcceptedDebuggerCommands /usr/bin/valgrind.bin" "CommandDebug"

  insertKeytoConfigFile "DebugOptions" "\n\
#\n\
# Append arguments to the command used by the server to launch the\n\
# debug tool\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\
#DebugOptions \\\"\\\"" "AcceptedDebuggerCommands"

  insertKeytoConfigFile "EnableClientAutoreconnect" "\n\
#\n\
# Enable or disable NoMachine clients trying to auto-reconnect when\n\
# the connection is lost. A comma-separated list of protocols can\n\
# be also provided.\n\
#\n\
# NX:   The auto-reconnection will be available only for clients\n\
#       connected by NX protocol.\n\
#\n\
# SSH:  The auto-reconnection will be available only for clients\n\
#       connected by SSH protocol.\n\
#\n\
# HTTP: The auto-reconnection will apply only to sessions connected\n\
#       via web.\n\
#\n\
# none: The auto-reconnection is disabled on all kind of connections.\n\
#\n\
#EnableClientAutoreconnect NX,SSH,HTTP" "DebugOptions"

  insertKeytoConfigFile "EnableLockScreen" "\n\
#\n\
# Activate the system lock screen when the NoMachine user disconnects\n\
# from the physical display.\n\
#\n\
# 1: Enabled. When the user disconnects, the physical screen of this\n\
#    host will be locked.\n\
#\n\
# 0: Disabled. When the user disconnects, the screen state will not\n\
#    change. This is the default.\n\
#\n\
#EnableLockScreen 0" "NXGssapiLibraryPath"

  insertKeytoConfigFile "LogoutOnDisconnect" "\n\
#\n\
# Enable or disable the automatic logout of the user from the system\n\
# upon disconnection of the NoMachine session.\n\
#\n\
# 1: Enabled. NoMachine will execute the forcelogout.sh script. The\n\
#    automatic logout can be effective only if the command set in\n\
#    script is appropriate for the system.\n\
#\n\
# 0: Disabled. When disconnecting the NoMachine session, the user is\n\
#    not automatically logged out of the system.\n\
#\n\
#LogoutOnDisconnect 0" "EnableLockScreen"

  insertKeytoConfigFile "LogoutOnDisconnectTimeout" "\n\
#\n\
# Delay the execution of the logout command when 'LogoutOnDisconnect'\n\
# is enabled. By default timeout is set to 0, i.e. the forcelogout.sh\n\
# script is executed immediately as soon as the user disconnects the\n\
# session. Specify a delay in seconds, for example 600 to execute the\n\
# logout after ten minutes.\n\
#\n\
#LogoutOnDisconnectTimeout 0" "LogoutOnDisconnect"

  insertKeytoConfigFile "EnableWebPreconfiguration" "\n\
#\n\
# Allow NoMachine HTTP Server to serve content of Web Player applica-\n\
# tion only when a connection file stored on the server is provided\n\
# in the URL.\n\
#\n\
# 1: Enabled. Users can run sessions on the web only through a\n\
# a connection file pre-configured on the server.\n\
#\n\
# 0: Disabled. Users can configure their web sessions at runtime\n\
# or can use pre-configured connection files stored on the\n\
# server or on their device. This is the default.\n\
#\n\
#EnableWebPreconfiguration 0" "EnableWebConnectionName"

  insertKeytoConfigFile "LoginScreenAccess" "\n\
#\n\
# Allow users to access the system login screen when connecting to\n\
# the physical display.\n\
#\n\
# 1: Enabled. Users can connect to the system login screen and insert\n\
#    their credentials to log-in to the physical desktop. This is the\n\
#    default.\n\
#\n\
# 0: Disabled. Users are not allowed to connect to the system login\n\
#    screen. Only system administrators, NoMachine administrators and\n\
#    trusted users are still able to log-in.\n\
#\n\
#LoginScreenAccess 1" "PhysicalDesktopAuthorization"

  insertKeytoConfigFile "ForceClientNewSession" "\n\
#\n\
# Force clients to start a new session at every connection. Server\n\
# will always send an empty list of available sessions, users will\n\
# be therefore not able to reconnect their Linux virtual desktops\n\
# and custom sessions or to connect to other users' desktops if any.\n\
# Specify 'all' to apply this setting to all users or provide a comma\n\
# separated list of usernames. Disable session persistence to force\n\
# the termination of virtual desktops and custom sessions. Set this\n\
# key to 'none' to allow the server to provide the ordinary list of\n\
# available sessions to the client. This is the default.\n\
#\n\
#ForceClientNewSession none" "EnableClientAutoreconnect"

  insertKeytoConfigFile "NXAuthorizedBasePath" "\n\
#\n\
# Specify the base path to the authorized keys file for connections\n\
# by NX protocol. By default it's the user's home directory. If a\n\
# custom path is specified, the server will add the user's name to\n\
# the base path, e.g. /tmp/nxtest01 on Linux. This key has to be used\n\
# in conjunction with NXAuthorizedRelativePath.\n\
#\n\
#NXAuthorizedBasePath \\\"\\\"" "ForceClientNewSession"

  insertKeytoConfigFile "NXAuthorizedRelativePath" "\n\
#\n\
# Specify the relative path to the authorized keys file and the file\n\
# name, by default authorized.crt. The base path to this file is\n\
# defined in NXAuthorizedBasePath.\n\
#\n\
#NXAuthorizedRelativePath .nx/config/authorized.crt" "NXAuthorizedBasePath"

  insertKeytoConfigFile "FailedSessionLimit" "\n\
#\n\
# In a multi-node environment exclude automatically a node from the\n\
# list of available nodes when the number of failed sessions on that\n\
# host exceed the limit. Default is 0, never exclude the node.\n\
#\n\
#FailedSessionLimit 0" "NXAuthorizedRelativePath"

  insertKeytoConfigFile "FailedSessionMinimumLifeTime" "\n\
#\n\
# Set the minimum time interval to be elapsed for including a failed\n\
# session in the counter for the failed session limit. Default is 60\n\
# seconds.\n\
#\n\
#FailedSessionMinimumLifeTime 60" "FailedSessionLimit"

  insertKeytoConfigFile "UserScriptAfterLogout" "\n\
#\n\
# Specify absolute path of the custom script to be executed after\n\
# the user is logged out. The script can accept username and remote\n\
# IP of the user's machine as its input.\n\
#\n\
#UserScriptAfterLogout \\\"\\\"" "UserScriptAfterLogin"

  insertKeytoConfigFile "NXKerberosUsePAM" "\n\
#\n\
# Enable or disable support for PAM account management when Kerberos\n\
# authentication is used in connections by NX protocol.\n\
#\n\
# 1: Enabled. Support for PAM account management is enabled.\n\
#\n\
# 0: Disabled. Support for PAM account management is disabled.\n\
#\n\
#NXKerberosUsePAM 1" "UserScriptAfterLogout"

  insertKeytoConfigFile "NXKeyBasedUsePAM" "\n\
#\n\
# Enable or disable support for PAM account management when public key\n\
# authentication is used in connections by NX protocol.\n\
#\n\
# 1: Enabled. Support for PAM account management is enabled.\n\
#\n\
# 0: Disabled. Support for PAM account management is disabled.\n\
#\n\
#NXKeyBasedUsePAM 1" "NXKerberosUsePAM"

  insertKeytoConfigFile "AutomaticRecordingAuthorization" "\n\
#\n\
# Enable, disable or restrict NX Server requesting authorization to\n\
# connecting users to allow the automatic recording of the session.\n\
#\n\
# 0: Disabled. The user is informed that his/her session will be\n\
#    recorded. If only a percentage of sessions is recorded,\n\
#    the user is notified about that possibility.\n\
#\n\
# 1: Enabled. The user can accept or refuse to allow NoMachine\n\
#    to record his/her session.\n\
#\n\
# 2: Restricted. The user can accept or refuse to allow NoMachine\n\
#    to record his/her session but in this last case the session\n\
#    will be terminated or disconnected in case of a virtual desktop.\n\
#\n\
#AutomaticRecordingAuthorization 1" "NXAuthorizedRelativePath"

  insertKeytoConfigFile "FailedSessionLimit" "\n\
#\n\
# In a multi-node environment exclude automatically a node from the\n\
# list of available nodes when the number of failed sessions on that\n\
# host exceed the limit. Default is 0, never exclude the node.\n\
#\n\
#FailedSessionLimit 0" "NXKeyBasedUsePAM"

  insertKeytoConfigFile "FailedSessionMinimumLifeTime" "\n\
#\n\
# Set the minimum time interval to be elapsed for including a failed\n\
# session in the counter for the failed session limit. Default is 60\n\
# seconds.\n\
#\n\
#FailedSessionMinimumLifeTime 60" "FailedSessionLimit"

  insertKeytoConfigFile "WebAccessType" "\n\
#\n\
# Configure access to the initial page displayed when connecting by\n\
# the web. Accepted values are:\n\
#\n\
# unrestricted: Users access the initial page without logging-in.\n\
#\n\
# systemlogin: Users need to provide their system credentials.\n\
#\n\
# networklogin: Users need to provide their credentials for NoMachine\n\
# Network login.\n\
#\n\
#WebAccessType unrestricted" "FailedSessionMinimumLifeTime"

  insertKeytoConfigFile "NXdConnectionsLimit" "\n\
#\n\
# Specify the maximum number of connections that the NX service can\n\
# accept. Further connections will be denied.\n\
#\n\
#NXdConnectionsLimit \\\"\\\"" "WebAccessType"

  insertKeytoConfigFile "NXdConnectionsInterval" "\n\
#\n\
# Specify the grace period in seconds, during which the connections\n\
# can accept connections up to the NXdConnectionsIntervalLimit.\n\
#\n\
#NXdConnectionsInterval \\\"\\\"" "NXdConnectionsLimit"

  insertKeytoConfigFile "NXdConnectionsIntervalLimit" "\n\
#\n\
# Specify the maximum number of connections that the NX service can\n\
# accept during the interval of time set in NXdConnectionsInterval.\n\
#\n\
#NXdConnectionsIntervalLimit \\\"\\\"" "NXdConnectionsInterval"

  insertKeytoConfigFile "NXdListenAddress" "\n\
#\n\
# Specify the network interface where the NX service will be bound.\n\
# Populate the field with an IP address or a domain name.\n\
#\n\
#NXdListenAddress \\\"\\\"" "NXdConnectionsIntervalLimit"

  insertKeytoConfigFile "WebReferrer" "\n\
#\n\
# Specify the referrers allowed to access the web player in a comma\n\
# separated list. If the referrer is not in the list, redirects the\n\
# user to the URL set in the WebRedirect key.\n\
#\n\
WebReferrer \\\"\\\"" "NXdListenAddress"

  insertKeytoConfigFile "WebRedirect" "\n\
#\n\
# Specify the URL for redirecting users when their referrer is not\n\
# allowed in the WebReferrer key.\n\
#\n\
WebRedirect \\\"\\\"" "WebReferrer"

  insertKeytoConfigFile "GuestDesktopSharing" "\n\
#\n\
# Enable or disable the guest desktop sharing functionality for the\n\
# Enterprise Desktop and NoMachine free versions.\n\
#\n\
# 0: Disabled. Users can connect to the physical desktop only with a\n\
#    valid account.\n\
#\n\
# 1: Enabled. Users can connect to the physical desktop as guests.\n\
#    Credentials are not required but the desktop owner has to allow\n\
#    access.\n\
#\n\
#GuestDesktopSharing 0" "WebRedirect"

  if [ "x${LICENSE_ACRONYM}" = "x" ];
  then
    getLicenseAcronym

    if [ "x${LICENSE_ACRONYM}" = "x" ];
    then
      printMsg "Cannot read license acronym" "warn"

      return 0
    fi
  fi

  if [ "x${LICENSE_ACRONYM:1:2}" = "xCS" ] || [ "x${LICENSE_ACRONYM:1:3}" = "xECS" ] || \
     [ "x${LICENSE_ACRONYM:1:1}" = "xS" ] || [ "x${LICENSE_ACRONYM:1:2}" = "xED" ];
  then

    insertKeytoConfigFile "EnableGuestAccess" "\n\
#\n\
#Enable or disable the guest user functionality.\n\
#\n\
# 0: Disabled. Only user with a valid account can get access.\n\
#\n\
# 1: Enabled. Users can connect to the desktops as guests.\n\
#\n\
#EnableGuestAccess 0" "GuestDesktopSharing"

  fi

  insertKeytoConfigFile "PhysicalDesktopGuestMode" "\n\
#\n\
#Set the interaction level for the session connected to the physical\n\
#desktop for guest users only:\n\
#\n\
# 0: View-only. The session is connected to the desktop in view-only\n\
#    mode, i.e. the guest can't interact with the physical desktop.\n\
#\n\
# 1: Restricted. Guest users connected to the physical desktop can\n\
#    interact with the desktop except for resize operations.\n\
#\n\
# 2: Interactive. Guests connected to the physical desktop have full\n\
#    interaction with the desktop.\n\
#\n\
#PhysicalDesktopGuestMode 2" "EnableGuestAccess"

  if [ "x${LICENSE_ACRONYM:1:3}" = "xETS" ] || [ "x${LICENSE_ACRONYM:1:2}" = "xTS" ];
  then
    insertKeytoConfigFile "EnableGuestCreateVirtualDesktop" "\n\
#\n\
#Enable or disable support for automatic provision of guest accounts.\n\
#\n\
# 0: Disabled. Only user with a valid account can get access.\n\
#\n\
# 1: Enabled. The automatic generation of guest accounts on demand.\n\
#\n\
#EnableGuestCreateVirtualDesktop 0" "GuestDesktopSharing"
  fi

  if [ "x${LICENSE_ACRONYM:1:3}" = "xETS" ] || [ "x${LICENSE_ACRONYM:1:2}" = "xTS" ] || \
     [ "x${LICENSE_ACRONYM:1:4}" = "xSBTS" ] || [ "x${LICENSE_ACRONYM:1:1}" = "xW" ];
  then

    insertKeytoConfigFile "VirtualDesktopGuestMode" "\n\
#\n\
# Set the interaction level for the session connected to a virtual\n\
# desktop for guest users only:\n\
#\n\
# 0: View-only. The session is connected to the desktop in view-only\n\
#    mode, i.e. the guest can't interact with the virtual desktop.\n\
#\n\
# 1: Restricted. Guest users connected to the virtual desktop can\n\
#    interact with the desktop except for resize operations.\n\
#\n\
# 2: Interactive. Guests connected to the virtual desktop have full\n\
#    interaction possibilities with the desktop.\n\
#\n\
#VirtualDesktopGuestMode 2" "GuestDesktopSharing"

  fi

  insertKeytoConfigFile "ConnectionsLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent connections reaches that value. This key\n\
# must be used in conjunction with the ConnectionsLimit key.\n\
#\n\
#ConnectionsLimitAlert 0" "ConnectionsLimit"

  insertKeytoConfigFile "ConnectionsUserLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent users reaches that value. This key\n\
# must be used in conjunction with the ConnectionsUserLimit key.\n\
#\n\
#ConnectionsUserLimitAlert 0" "ConnectionsUserLimit"

  insertKeytoConfigFile "VirtualDesktopsLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent users reaches that value. This key\n\
# must be used in conjunction with the VirtualDesktopsLimit key.\n\
# The alert threshold should not be higher than the number of virtual\n\
# desktops allowed by the license.\n\
#\n\
#VirtualDesktopsLimitAlert 0" "VirtualDesktopsLimit"

  insertKeytoConfigFile "VirtualDesktopsUserLimitAlert" "\n\
#\n\
# Specify the threshold for printing an alert into server log when\n\
# the number of concurrent users reaches that value. This key\n\
# must be used in conjunction with the VirtualDesktopsUserLimit key.\n\
#\n\
#VirtualDesktopsUserLimitAlert 0" "VirtualDesktopsUserLimit"

  insertKeytoConfigFile "UserScriptAfterLimitAlarm" "\n\
#\n\
# Specify absolute path of the custom script to be executed when any\n\
# of the threshold alarms set for users or connections limits is\n\
# reached. The script can accept username, client IP, type of alarm\n\
# (for connections, users connections, virtual desktops and users\n\
# virtual desktops limit) as its input.\n\
#\n\
#UserScriptAfterLimitAlarm \\\"\\\"" "VirtualDesktopsUserLimitAlert"

  insertKeytoConfigFile "PhysicalDesktopAccessNodes" "\n\
#\n\
# Allow the given type of users to connect to the physical desktop\n\
# of any of the available nodes. Set this key to 'all' to allow all\n\
# kind of users, or to 'none' to completely forbid access to the\n\
# physical desktop. Otherwise give a comma-separated list of values\n\
# to indicate which type of users is allowed to connect, order is not\n\
# relevant and accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users for connections to physical\n\
#                desktop.\n\
#\n\
# system:        all unprivileged users who have a valid account to\n\
#                login.\n\
#\n\
# owner:         the owner of the remote desktop.\n\
#\n\
# guest:         Guest Desktop Sharing users.\n\
#\n\
#PhysicalDesktopAccessNodes administrator,trusted,owner,system" "VirtualDesktopGuestMode"

  insertKeytoConfigFile "VirtualDesktopAccessNodes" "\n\
#\n\
# Allow the given type of users to connect to a virtual desktop on\n\
# any of the remote nodes. Set this key to 'all' to allow all kind\n\
# of users, or to 'none' to completely forbid connections to already\n\
# running virtual desktops. Otherwise give a comma-separated list of\n\
# values to indicate which type of users is allowed to connect, order\n\
# is not relevant and accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users for connections to virtual\n\
#                desktops.\n\
#\n\
# system:        all unprivileged users who have a valid account to\n\
#                login.\n\
#\n\
# owner:         the owner of the remote desktop.\n\
#\n\
# guest:         Guest Desktop Sharing users.\n\
#\n\
#VirtualDesktopAccessNodes administrator,trusted,owner,system" "PhysicalDesktopAccessNodes"

  insertKeytoConfigFile "NodePingTimeout" "\n\
#\n\
# Specify the frequency with which the server has to send the ping\n\
# message to verify if the remote node is reachable. By default ping\n\
# is sent every 10 seconds.\n\
#\n\
#NodePingTimeout \\\"180\\\"" "VirtualDesktopAccessNode"

  insertKeytoConfigFile "NodePingInterval" "\n\
#\n\
# Specify for how long the server has to wait for a reply from the\n\
# remote node before considering it unreachable. Default value is\n\
# 10 seconds.\n\
#\n\
#NodePingInterval \\\"10\\\"" "NodePingTimeout"

  insertKeytoConfigFile "ClientNodeTunnelConnectionTimeout" "\n\
#\n\
# Specify for how long a client should try to connect directly to the\n\
# node before switching to tunnel the connection. This requires that\n\
# the node has the tunnel method set for the client connections.\n\
# Default timeout value is 5 seconds.\n\
#\n\
#ClientNodeTunnelConnectionTimeout 5" "NodePingInterval"

  insertKeytoConfigFile "ClientNodeDirectConnectionTimeout" "\n\
#\n\
# Specify for how long a client should try to connect directly to the\n\
# node before considering that the connection cannot be established.\n\
# Default value is 30 seconds.\n\
#\n\
#ClientNodeDirectConnectionTimeout 30" "ClientNodeTunnelConnectionTimeout"

  insertKeytoConfigFile "ServerNodeConnectionTimeout" "\n\
#\n\
# Specify for how long the server should try to connect to the remote\n\
# node before considering that the tunnel cannot be established.\n\
# Default value is 10 seconds.\n\
#\n\
#ServerNodeConnectionTimeout 10" "ClientNodeDirectConnectionTimeout"

  insertKeytoConfigFile "ServerNodeControlConnectionTimeout" "\n\
#\n\
# Specify for how long the process monitoring the remote node should\n\
# wait before considering that the connection with the node is lost.\n\
# Default value is 30 seconds.\n\
#\n\
#ServerNodeControlConnectionTimeout 30" "ServerNodeConnectionTimeout"

  insertKeytoConfigFile "ServerName" "\n\
#\n\
# This is the name nodes will see in the notifications coming from\n\
# this cloud server.\n\
#\n\
#ServerName \\\"\\\"" "ServerNodeControlConnectionTimeout"

  insertKeytoConfigFile "ScriptAfterClusterSync" "\n\
#\n\
# The execution of custom scripts for the NoMachine cluster requires\n\
# to add the same script on both peers (master and slave servers of\n\
# the cluster)\n\
#\n\
# Specify absolute path of the script to be executed after\n\
# the cluster synchronization.\n\
#\n\
#ScriptAfterClusterSync \\\"\\\"" "ServerName"

  insertKeytoConfigFile "ScriptClusterSetSharedIP" "\n\
#\n\
# Specify absolute path of the script to create the shared IP of the\n\
# cluster on the active peer when the cluster is started, i.e. after\n\
# that the cluster is configured or once a failover occurred.\n\
#\n\
#ScriptClusterSetSharedIP \\\"\\\"" "ScriptAfterClusterSync"

  insertKeytoConfigFile "ScriptClusterClearSharedIP" "\n\
#\n\
# Specify absolute path of the script to clean up the cluster shared\n\
# IP after events like 'clusterdel', 'shutdown' and 'restart'. The\n\
# shared IP will be created again when configuring the cluster or\n\
# when starting it after a shutdown.\n\
#\n\
#ScriptClusterClearSharedIP \\\"\\\"" "ScriptClusterSetSharedIP"

  insertKeytoConfigFile "EnableCommunicationHub" "\n\
#\n\
# Enable or disable making this cloud server the only communication\n\
# hub for the NoMachine traffic, included NoMachine Network traffic.\n\
#\n\
# 1: Enabled. Tunnel all the NoMachine traffic through this cloud\n\
#    server.\n\
#\n\
# 0: Disabled. The NoMachine traffic is tunneled or forwarded to\n\
#    the nodes depending on how they are configured.\n\
#\n\
#EnableCommunicationHub 0" "ScriptClusterClearSharedIP"

  insertKeytoConfigFile "EnableNetworkAutomaticConnection" "\n\
#\n\
# Enable or disable this server to connect automatically to NoMachine\n\
# Network at startup.\n\
#\n\
# 1: Enabled. Make this machine available on NoMachine Network auto-\n\
#    matically.\n\
#\n\
# 0: Disabled. Connect manually this machine to NoMachine Network.\n\
#\n\
#EnableNetworkAutomaticConnection 1" "NXKerberosRequestLimit"

  insertKeytoConfigFile "PhysicalDesktopAcceptUsers" "\n\
#\n\
# Allow specific users to accept connections of other users to the\n\
# physical desktop. By default, only the owner can accept. Set this\n\
# key to 'all' to allow all types of users, or to 'none' to forbid\n\
# any user from accepting. Provide a comma-separated list of values\n\
# to indicate which type of users can accept. Order is not relevant.\n\
# Accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users.\n\
#\n\
# system:        unprivileged users with a valid account.\n\
#\n\
# owner:         the owner of the physical desktop.\n\
#\n\
# guest:         Guest Desktop Sharing users who login anonymously\n\
#                    to cloud server and nodes without having a system\n\
#                    account and system guests with an account generated\n\
#                    on demand on Linux terminal server nodes.\n\
#\n\
#PhysicalDesktopAcceptUsers owner" "PhysicalDesktopAccessNoAcceptance"

  insertKeytoConfigFile "VirtualDesktopAcceptUsers" "\n\
#\n\
# Allow specific users to accept connections of other users to the\n\
# virtual desktop. By default, only the owner can accept. Set this\n\
# key to 'all' to allow all types of users, or to 'none' to forbid\n\
# any user from accepting. Provide a comma-separated list of values\n\
# to indicate which type of users can accept. Order is not relevant.\n\
# Accepted values are:\n\
#\n\
# administrator: system and NoMachine administrators.\n\
#\n\
# trusted:       NoMachine trusted users.\n\
#\n\
# system:        unprivileged users with a valid account.\n\
#\n\
# owner:         the owner of the virtual desktop.\n\
#\n\
# guest:         Guest Desktop Sharing users who login anonymously\n\
#                    to cloud server and nodes without having a system\n\
#                    account and system guests with an account generated\n\
#                    on demand on Linux terminal server nodes.\n\
#\n\
#VirtualDesktopAcceptUsers owner" "VirtualDesktopAccessNoAcceptance"

  insertKeytoConfigFile "EnableWebAutocomplete" "\n\
#\n\
# Allow the Web Player to autocomplete the Username field or not.\n\
#\n\
# 1: Enabled. The Username field in the login form has autocomplete\n\
#    active.\n\
#\n\
# 0: Disabled. The Username field is not completed automatically.\n\
#    Autocomplete is always disabled for the Password field.\n\
#\n\
#EnableWebAutocomplete 1" "VirtualDesktopAcceptUsers"

  #
  # This SED command handle all misstypes.
  #

  ${SEDCOMMAND} -e 's/viceversa/vice versa/g' \
                -e 's/protoype/prototype/g' \
                -e 's/dsupport/support/g' \
                "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

  commandRestoreFile "${CONFIG_FILE}" "tmp"

  #
  # Updating server.cfg key name.
  #

  renameKey "EnableScreenLock" "EnableScreenBlanking";
  renameKey "EnableServerRole" "EnableDirectConnections";
  renameKey "NXPort" "NXTCPPort";
  renameKey "NXUPnPPort" "NXUDPUPnPPort";
  renameKey "SSHDUPnPPort" "SSHUPnPPort";
  renameKey "SSHDPort" "SSHPort";

  getValueFromCfgFile "UserId" "${CONFIG_FILE}"

  if [ "x${cfg_val}" = "x10" ];
  then
    ${SEDCOMMAND} -e 's|^#UserId 10$|#UserId \"\"|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  getValueFromCfgFile "GuestUserGroup" "${CONFIG_FILE}"

  if [ "x${cfg_val}" = "xguest" ];
  then
    ${SEDCOMMAND} -e 's|^#GuestUserGroup guest$|#GuestUserGroup \"\"|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  getValueFromCfgFile "UserGroup" "${CONFIG_FILE}"

  if [ "x${cfg_val}" = "xusers" ];
  then
    ${SEDCOMMAND} -e 's|^#UserGroup users$|#UserGroup \"\"|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  getValueFromCfgFile "UserHome" "${CONFIG_FILE}"

  if [ "x${cfg_val}" = "x/home" ];
  then
    ${SEDCOMMAND} -e 's|^#UserHome /home$|#UserHome \"\"|g' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  #
  # Removing wrong description.
  #

  output=$(${GREPCOMMAND} -A1 "# the new user." "${CONFIG_FILE}" | ${TAILCOMMAND} -1)

  if [ "${output}x" = "#x" ]
  then
    ${AWKCOMMAND} '/# the new user./{getline;next}{print}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  else
    ${AWKCOMMAND} '/# the new user./{getline}{print}' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"
    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  #
  # Update description of PhysicalDesktopMode
  #

  command="${GREPCOMMAND} '1: Restricted\. User connected to the physical desktop can' '${CONFIG_FILE}'"
  outCommand=$(${BASHSHELL} -c "${command}" 2>&1)

  if [ $? != 0 ];
  then
    ${SEDCOMMAND} -e 's/1: Interactive\. User connected to the physical desktop has/1: Restricted. User connected to the physical desktop can\
#    interact with the desktop except for resize operations.\
#\
# 2: Interactive. User connected to the physical desktop has/' "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

    ${SEDCOMMAND} -e 's/PhysicalDesktopMode 1/PhysicalDesktopMode 2/' -e 's/1: Interactive/2: Interactive/' "${CONFIG_FILE}.tmp" > "${CONFIG_FILE}"
  fi

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

  #
  # Update PhysicalDesktopSharing.
  #

  grep_out=$("$GREPCOMMAND" "# 2: Restricted. Only the administrator and trusted users" \
             "$CONFIG_FILE" 2>/dev/null)

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

    "${AWKCOMMAND}" '/# Allow the user to connect to the physical desktop:/ {f=1} !f;\
                    /# 0: Disabled. Connections to the physical desktop are/ \
                    {print \
                    "# Allow the user to connect to the physical desktop:\n#\n# 0: Disabled. Connections to the physical desktop are\n#    forbidden.\n#\n# 1: Enabled. Each user can request to connect to the\n#    physical desktop.\n#\n# 2: Restricted. Only the administrator and trusted users\n#    can connect to the physical desktop."; \
                    f=0; getline}' \
                    "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"

    getValueFromCfgFile "PhysicalDesktopSharing" "$CONFIG_FILE"

    if [ "x$ret_getValueFromCfgFile" = "x1" ] && [ "x$cfg_val" = "x1" ];
    then
      setValueAtCfgFile "$CONFIG_FILE" "#PhysicalDesktopSharing" "2"
    fi
  fi

  #
  # Update description of EnableServerRole.
  #

  grep_out=$("$GREPCOMMAND" "# Enable or disable this server accepting direct connections to its" \
             "$CONFIG_FILE" 2>/dev/null)

  if [ "x${grep_out}" = "x" ];
  then
    "${AWKCOMMAND}" '/# Enable or disable server role of this server when it'\''s configured/ {f=1} !f;\
                     /# 0: Disabled. Users are not allowed to connect to this server. To/ \
                     {print \
                     "# Enable or disable this server accepting direct connections to its\n# IP or hostname when it'\''s federated in a multi-server environment.\n#\n# 1: Enabled. Users are allowed to connect to this NoMachine server.\n#\n# 0: Disabled. Users have to connect to the main server ruling the\n#    multi-host environment in order to reach this server."; \
                     f=0; getline}' \
                     "${CONFIG_FILE}" > "${CONFIG_FILE}.tmp"

    commandRestoreFile "${CONFIG_FILE}" "tmp"
  fi

  #
  # Update AcceptedAuthenticationMethods.
  #

  grep_out=$("$GREPCOMMAND" "# Supported methods for connections by SSH protocol are:" \
             "$CONFIG_FILE" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    "$SEDCOMMAND" -e 's/# Supported methods for connections by SSH protocol are:/# Supported method for connections by SSH protocol is:/g' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"
  fi

  grep_out=$("$GREPCOMMAND" "# SSH-nomachine : Server-based DSA key and password authentication." \
             "$CONFIG_FILE" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    "$SEDCOMMAND" -e '/# SSH-nomachine : Server-based DSA key and password authentication./d' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"
  fi

  grep_out=$("$GREPCOMMAND" "# SSL client authentication for connections by NX protocol." \
             "$CONFIG_FILE" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    "$SEDCOMMAND" -e 's/# SSL client authentication for connections by NX protocol./# client authentication for connections by NX protocol./g' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"
  fi

  #
  # Update ClientCredentialsStoring
  #

  grep_out=$("$GREPCOMMAND" "# 1: Enabled. Users can save username and password in their connection" \
             "$CONFIG_FILE" 2>/dev/null)

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

    "$AWKCOMMAND" "/# Enable or disable users to store their access credentials on their/\
                  {f=1} !f; /# *from saving their credentials./ \
    {print \"# Enable or disable users to store their access credentials on their\";
     print \"# devices when they connect via NoMachine client or in the browser's\";
     print \"# cookie in case of web sessions. Accepted values are:\";
     print \"#\";
     print \"# player:    Allow only users connected via NoMachine client to save\";
     print \"#            username and password in their connection file.\";
     print \"#\";
     print \"# webplayer: Allow only users connected via web to store username and\";
     print \"#            password in the browser's cookies, if enabled.\";
     print \"#\";
     print \"# both:      Users connected via client or via web can always choose to\";
     print \"#            store their credentials.\";
     print \"#\";
     print \"# none:      Do not permit users to save their username and password.\";
     print \"#            Users will be requested to insert their credentials at\";
     print \"#            each new connection via NoMachine client or web.\";
                  f=0}" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"

    "$SEDCOMMAND" 's/EnableClientCredentialsStoring[[:space:]]*1/EnableClientCredentialsStoring both/g'\
    "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"

    "$SEDCOMMAND" 's/EnableClientCredentialsStoring[[:space:]]*0/EnableClientCredentialsStoring none/g'\
    "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"

  fi

  grep_out=$("$GREPCOMMAND" "# Enable or disable NX Server requests to the connected user to make" \
             "$CONFIG_FILE" 2>/dev/null)

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

    "$AWKCOMMAND" "/# Enable or disable NX Server requests to the connected user to make/\
                  {f=1} !f; /#    user\.$/ \
    {print \"# Configure the NX Server behavior when the maximum number of allowed\";
     print \"# connections is reached. An already connected user can be asked to\";
     print \"# accept or refuse to disconnect to make room for the incoming user\";
     print \"# this is the default, or can be automatically disconnected or\";
     print \"# never disconnected.\";
     print \"#\";
     print \"# 0: Disabled. The server prompts the connected user to accept or\";
     print \"#    refuse to disconnect for making room for the incoming user. If\";
     print \"#    no choice is made, the user is automatically disconnected.\";
     print \"#\";
     print \"# 1: Enabled. The server automatically disconnects the connected user\";
     print \"#    to make room for the connecting user. No message is issued to\";
     print \"#    the already connected user.\";
     print \"#\";
     print \"# 2: None. The server prompts the connected user to accept or\";
     print \"#    refuse to disconnect for making room for the incoming user. If\";
     print \"#    no choice is made, the server doesn't disconnect the user and\";
     print \"#    advise the incoming user that the maximum number of allowed\";
     print \"#    connections is reached.\";
     print \"#\";
     print \"# 3: Silent. The server never notifies desktop owners about incoming\";
     print \"#    users, incoming users are informed that the maximum number of\";
     print \"#    allowed connections is reached.\";
                  f=0}" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"

  fi

  grep_out=$("$GREPCOMMAND" "#    a connection file pre-configured on the server." \
                            "$CONFIG_FILE" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
    "$SEDCOMMAND" -e 's/# 1: Enabled. Users can run sessions on the web only through a/# 1: Enabled. Users can run sessions on the web only through the/g' \
                  -e 's/#    a connection file pre-configured on the server./#    default.nxs file or another connection file pre-configured\
#    on the server./g' "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"
  fi

  grep_out=$("$GREPCOMMAND" "# values are: 'round-robin' for selecting the node according to the" \
             "$CONFIG_FILE" 2>/dev/null)

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

    "$AWKCOMMAND" "/# values are: 'round-robin' for selecting the node according to the/\
                  {f=1} !f; /LoadBalancingAlgorithm/ \
     {print \"# values are:\";
      print \"#\";
      print \"# round-robin:  the server applies a plain round-robin algorithm to\";
      print \"#               choose the node or a weighted round-robin algorithm\";
      print \"#               if weight has been specified for each node. This is\";
      print \"#               the default.\";
      print \"#\";
      print \"# custom:       the server uses the custom load-balancing algorithm\";
      print \"#               specified in the NodeSelectionScript key.\";
      print \"#\";
      print \"# load-average: the server chooses the node with the minimum load\";
      print \"#               average provided by the system.\";
      print \"#\";
      print \"# system-load:  the server selects the node with the lowest system\";
      print \"#               load calculated according to the algorithm specified\";
      print \"#               in the nxreportsystemload.pl script set on the node.\";
      print \"#\";
      print;
            f=0}" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"

  fi

  grep_out=$("$GREPCOMMAND" "# xsessions=1    list all desktop types available in /usr/share/xsessions." \
                            "$CONFIG_FILE" 2>/dev/null)

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

     "$AWKCOMMAND" "/# dialog=1       display the disconnect\/terminate dialog./\
                   {f=1} !f; /ConnectPolicy/ \
     {print \"# dialog=1       display the disconnect/terminate dialog.\";
      print \"#\";
      print \"# xsessions=1    list all desktop types available in /usr/share/xsessions.\";
      print \"#\";
      print \"# udp=1          enable UDP with value 1, disable it with value 0.\";
      print \"#\";
      print;
            f=0}" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

     commandRestoreFile "$CONFIG_FILE" "tmp"

     "$SEDCOMMAND" 's/\(ConnectPolicy autocreate=.,autoconnect=.,automigrate=.,desktop=.,dialog=.\)$/\1,xsessions=0,udp=1/' \
                      "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

     commandRestoreFile "$CONFIG_FILE" "tmp"

  fi

  grep_out=$("$GREPCOMMAND" "# 6: This is the default value. Only the important events" \
                            "$CONFIG_FILE" 2>/dev/null)

  if [ "x${grep_out}" != "x" ];
  then
     "$AWKCOMMAND" "/# Set the log level of NX Server. NX Server logs to the syslog all/\
                  {f=1} !f; /# 7: Sets logs to level debug./ \
     {print \"# Set the log level of NX Server. NX Server logs to the syslog all\";
      print \"# the events that are <= to the level specified below, according to\";
      print \"# the following conventions.\";
      print \"#\";
      print \"# Note that NX Server uses level 6 in the syslog to log the event.\";
      print \"# This is intended to override settings on the local syslog configur-\";
      print \"# ation that would prevent the event from being actually logged.\";
      print \"#\";
      print \"# The suggested values are:\";
      print \"#\";
      print \"# 5: Only relevant events are logged such as established client\";
      print \"#    connections, errors and warnings.\";
      print \"#\";
      print \"# 6: This is the default value. Important events are logged such as\";
      print \"#    established client connections, login, session startup, logout,\";
      print \"#    errors and warnings.\";
      print \"#\";
            f=0}" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"

    "$SEDCOMMAND" 's/# 7: Sets logs to level debug./# 7: Debug log level./g'\
    "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

    commandRestoreFile "$CONFIG_FILE" "tmp"
  fi

  #
  # Merging keys from old cloud.cfg to gain unificated server.cfg in all NoMachine products.
  #

  isSupportedHtd

  if [ ${ret_isSupportedHtd} -ne 1 ];
  then
    mergeCloudCfgDefaults
  fi

  #
  # Remove keys.
  #

  removeOptionFromCfgNew "EnableNodeMonitoring" "Enable *or *disable *monitoring.*ode"
  removeOptionFromCfgNew "NodeResponseTimeout" "Set *for *how *long.*erver *daemon *has.*wait.*reply"
  removeOptionFromCfgNew "InstallationType" "Specify *whether *this *installation *can *accept *requests *to *connect"

  getValueFromCfgFile "EnableScreenBlanking" "$CONFIG_FILE"

  if [ $ret_getValueFromCfgFile = 2 ];
  then
    setValueAtCfgFile "$NX_ROOT/etc/node.cfg" "EnableScreenBlanking" "$cfg_val"
  fi

  removeOptionFromCfgNew "EnableScreenBlanking" "Blanking.*physical screen of the machine when somebody connects."
  removeOptionFromCfgNew "EnableGSSAPIAuthentication" "Enable.*disable *support *for *Kerberos *tickets"

  if [ "x${LICENSE_ACRONYM:1:3}" != "xETS" ] && [ "x${LICENSE_ACRONYM:1:2}" != "xTS" ] && \
     [ "x${LICENSE_ACRONYM:1:4}" != "xSBTS" ] && [ "x${LICENSE_ACRONYM:1:1}" != "xW" ];
  then
    removeOptionFromCfgNew "EnableGuestAccessVirtualDesktop" "Enable.*disable.*guest *virtual *desktop.*functionality"
    removeOptionFromCfgExtended  "# Set the interaction level for the session connected to a virtual"  \
                                 "# desktop for guest users only:" \
                                 "#VirtualDesktopGuestMode 2"
  fi

  if [ "x${LICENSE_ACRONYM:1:1}" != "xS" ] && [ "x${LICENSE_ACRONYM:1:2}" != "xED" ];
  then
    removeOptionFromCfgExtended "# Set the interaction level for the session connected to the physical" \
                                "# desktop for guest users only:" \
                                "#PhysicalDesktopGuestMode 2"
  fi

  if [ "x${LICENSE_ACRONYM:1:3}" != "xETS" ] && [ "x${LICENSE_ACRONYM:1:2}" != "xTS" ];
  then
    removeOptionFromCfgNew "EnableGuestCreateVirtualDesktop" "Enable.*disable.*automatic *provision.*guest *accounts"
  fi

  if [ "x${LICENSE_ACRONYM:1:2}" != "xCS" ] && [ "x${LICENSE_ACRONYM:1:3}" != "xECS" ] && \
     [ "x${LICENSE_ACRONYM:1:1}" != "xS" ] && [ "x${LICENSE_ACRONYM:1:2}" != "xED" ];
  then
    removeOptionFromCfgNew "EnableGuestAccess" "Enable or disable the guest user functionality."
  fi

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

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

    "$AWKCOMMAND" "/# 0: Disabled. This is the default value, webplayer and webclient/\
                  {f=1} !f; /# *will log to the file specified in the SystemLogFile key./ \
    {print \"# 0: Disabled. This is the default value, the node will log to\";
     print \"#    the home of the session owner or to the path specified in\";
     print \"#    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

  removeOptionFromCfgNew "EnableSubscriptionReminder" "Enable.*disable *printing.*message.*inform *administrators *that"

  compareVersions "$previous_version" "7.6.0"

  if [ "$ret_compareVersions" -eq 2 ];
  then
    "$SEDCOMMAND" -e 's/^#VirtualDesktopsLimit 20/#VirtualDesktopsLimit 0/g' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"

    "$SEDCOMMAND" -e 's/^#VirtualDesktopsUserLimit 20/#VirtualDesktopsUserLimit 0/g' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"

    "$SEDCOMMAND" -e 's/^#ConnectionsLimit 20/#ConnectionsLimit 0/g' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"

    "$SEDCOMMAND" -e 's/^#ConnectionsUserLimit 20/#ConnectionsUserLimit 0/g' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"

    "$SEDCOMMAND" -e 's/^#DisplayLimit 200/#DisplayLimit 0/g' \
                  "$CONFIG_FILE" > "$CONFIG_FILE.tmp"
    commandRestoreFile "$CONFIG_FILE" "tmp"

  fi

  updateDesktopSharingKeys

  return
}

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

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

  if [ -d /usr/share/polkit-1/actions ];
  then

    if [ "${NX_ROOT}" != "/usr/NX" ];
    then
      if ${SEDCOMMAND} -e 's:/usr/NX:'"${NX_ROOT}"':' < "${NX_ROOT}/share/policy/org.freedesktop.pkexec.nomachine.policy" > "${NX_ROOT}/share/policy/org.freedesktop.pkexec.nomachine.policy.tmp"
      then
        commandRestoreFile "${NX_ROOT}/share/policy/org.freedesktop.pkexec.nomachine.policy" "tmp"
      fi
    fi

    commandCp "${NX_ROOT}/share/policy/org.freedesktop.pkexec.nomachine.policy" \
              "/usr/share/polkit-1/actions/" "warn"

    commandChmod "0644" "/usr/share/polkit-1/actions/org.freedesktop.pkexec.nomachine.policy"
  fi

}

uninstallPolicyFiles ()
{
  commandRmIfExist "/usr/share/polkit-1/actions/org.freedesktop.pkexec.nomachine.policy" "warn"
}

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

resetSSHMethod ()
{
  getLicenseAcronym "${NX_ROOT}/etc/server.lic"

  if [ "x${ret_getLicenseAcronym}" = "xLS" ];
  then
    getLicenseAcronym "${NX_ROOT}/etc/server.lic.sample"

     if [ "x${ret_getLicenseAcronym}" != "xLS" ];
     then
       setValueAtCfgFile "${CONFIG_FILE}" "ClientConnectionMethods" "NX,SSH"
     fi
  fi
}

setSSHClientKey ()
{

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

  whichPath "SSHClient"

  if [ "x${which_out}" != "x" ];
  then
    changeKeyAtConfigFile "${CONFIG_FILE}" "SSHClient" "${which_out}"
  fi
}

addServerDaemonFileApple ()
{
  if [ "${system}" = "macosx" ];
  then
    commandInstall "root" "${ROOTGNAME}" "0644" \
                   "${NX_ROOT}/share/mac/launchd/com.nomachine.server.plist" \
                   "/Library/LaunchDaemons/"
  fi
}

addNxdDaemonFileApple ()
{
  if [ "${system}" = "macosx" ];
  then
    commandInstall "root" "${ROOTGNAME}" "0644" \
                   "${NX_ROOT}/share/mac/launchd/com.nomachine.nxd.plist" \
                   "/Library/LaunchDaemons/"
  fi
}

removeServerDaemonFileApple ()
{
  if [ "${system}" = "macosx" ];
  then
    out=$(${LAUNCHCTLCOMMAND} list | ${GREPCOMMAND} "nomachine\.server$" 2>/dev/null)

    if [ "x${out}" != "x" ];
    then
      runCommand "${LAUNCHCTLCOMMAND} unload -w /Library/LaunchDaemons/com.nomachine.server.plist" "Cannot uninstall server plist file"
    fi

    commandRm "/Library/LaunchDaemons/com.nomachine.server.plist"
  fi
}

removeLocalServerDaemonFileApple ()
{
  if [ "${system}" = "macosx" ];
  then
    commandRmIfExist "/Library/LaunchAgents/com.nomachine.localnxserver.plist"
  fi
}

removeHtdServerDaemonFileApple ()
{
  if [ "${system}" = "macosx" ];
  then
    commandRmIfExist "/Library/LaunchDaemons/com.nomachine.nxhtd.plist"
  fi
}

removeNxdDaemonFileApple ()
{
  if [ "${system}" = "macosx" ];
  then
    out=$(${LAUNCHCTLCOMMAND} list | ${GREPCOMMAND} "nomachine\.nxd$" 2>/dev/null)

    if [ "x${out}" != "x" ];
    then
      runCommand "${LAUNCHCTLCOMMAND} unload -w /Library/LaunchDaemons/com.nomachine.nxd.plist" "Cannot uninstall nxd plist file"
    fi

    commandRm "/Library/LaunchDaemons/com.nomachine.nxd.plist"
  fi
}

removeNxhtdDaemonFileApple ()
{
  if [ "${system}" = "macosx" ];
  then
    out=$(${LAUNCHCTLCOMMAND} list | ${GREPCOMMAND} "nomachine\.nxhtd" 2>/dev/null)

    if [ "x${out}" != "x" ];
    then
      runCommand "${LAUNCHCTLCOMMAND} unload -w /Library/LaunchDaemons/com.nomachine.nxhtd.plist" "Cannot uninstall nxhtd plist file"
    fi

    commandRm "/Library/LaunchDaemons/com.nomachine.nxhtd.plist"
  fi
}

createServerLogFile ()
{
  if [ ! -f "${NX_VAR_DIR}/log/server.log" ];
  then
    commandTouch "${NX_VAR_DIR}/log/server.log" "warn"
  fi

  if [ "${system}" = "macosx" ];
  then
    commandChownChmod "${USER_NX}:${ROOTGNAME}" "0600" \
                      "${NX_VAR_DIR}/log/server.log"
  else
    commandChownChmod "${USER_NX}:${ROOTGNAME}" "0600" \
                      "${NX_VAR_DIR}/log/server.log"
  fi
}

createNxdCert ()
{
  if [ ! -e "${NX_ROOT}/etc/keys/host/nx_host_rsa_key" ];
  then
    if [ ! -e "${NX_ROOT}/etc/keys/host/nx_host_rsa_key.crt" ];
    then

      runCommand "NX_SYSTEM="${NX_ROOT}"\
                     LD_LIBRARY_PATH='${NX_ROOT}/lib:${NX_ROOT}/lib:$LD_LIBRARY_PATH'\
                         '${NXKEYGENCOMMAND}' -k '${NX_ROOT}/etc/keys/host/nx_host_rsa_key' -c '${NX_ROOT}/etc/keys/host/nx_host_rsa_key.crt'" "Failed to run '${NXKEYGENCOMMAND}'"

      commandChownChmod "${USER_NX}:${ROOTGNAME}" "0600" \
                        "${NX_ROOT}/etc/keys/host/nx_host_rsa_key"
      commandChownChmod "${USER_NX}:${ROOTGNAME}" "0644" \
                        "${NX_ROOT}/etc/keys/host/nx_host_rsa_key.crt"
    fi
  fi
}

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

  if [ ! -h "${NX_ROOT}/scripts/vgl/libGL.so" ];
  then
    commandLn "${NX_ROOT}/scripts/vgl/libvglfaker.so" \
              "${NX_ROOT}/scripts/vgl/libGL.so" "warn"
  fi

  commandChownChmod "root:${ROOTGNAME}" "0755" "${NX_ROOT}/scripts/vgl/vglrun"
  commandChownChmod "root:${ROOTGNAME}" "0755" \
                    "${NX_ROOT}/scripts/vgl/vglserver_config"
  commandChownChmod "root:${ROOTGNAME}" "0755" \
                    "${NX_ROOT}/scripts/vgl/vglgenkey"

  return 0

  #
  # Do not run vglserver_config script during installation
  #

  runCommand "${NX_ROOT}/scripts/vgl/vglserver_config -config" \
             "Cannot run vglserver_config" "warn"
  if [ $ret_runCommand = 0 ];
  then
    getNodeConfigFile

    commandTouch "${NX_ROOT}/.vgl_reboot"
  fi
}

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

  if [ -x "${NX_ROOT}/scripts/vgl/vglserver_config" ];
  then
    runCommand "${NX_ROOT}/scripts/vgl/vglserver_config -unconfig" \
               "Cannot unconfig vgl" "warn"
  fi
}

__installResources__ ()
{
  printMsgDebug "Install ${PACKAGE} resources"

  createMenuEntries
}

__installResourcesXDG__ ()
{
  printMsgDebug "Install node resources XDG"

  install_xdg_ok=0

  if [ "x${NX_MPKG_PACKAGE}" != "x${PACKAGE_NAME}" ];
  then
    if [ "x${NX_MPKG_PACKAGE}" != "xnode" ];
    then
      return 0
    fi
  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 ${PACKAGE} resources"

  removeMenuEntries
}

__uninstallResourcesXDG__ ()
{
  uninstall_xdg_ok=0

  if [ "x${NX_MPKG_PACKAGE}" != "x${PACKAGE_NAME}" ];
  then
    if [ "x${NX_MPKG_PACKAGE}" != "xnode" ];
    then
      return 0
    fi
  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 a standard way."
  fi

  if [ $uninstall_xdg_ok = 0 ];
  then
    __uninstallResources__
  fi
}

getXCookie()
{
  XAUTH_VAR="$($PSCOMMAND ax | $GREPCOMMAND "Xorg.* :0" 2>/dev/null | \
             $GREPCOMMAND auth 2>/dev/null | \
             $SEDCOMMAND 's/.*\(-auth \)\([^[:space:]]*\).*/\2/')"
}

getDisplay()
{
  PID_GNOME_SOFTWARE="$($FUSERCOMMAND "$DEBCONF_PIPE" 2>&1 | \
                        $SEDCOMMAND 's|'"$DEBCONF_PIPE"':||g' | \
                        $TRCOMMAND -d '[:space:]')"

  DISP_VAR="$($CATCOMMAND "/proc/$PID_GNOME_SOFTWARE/environ" | \
              $TRCOMMAND '\0' '\n' | $GREPCOMMAND DISPLAY 2>/dev/null | \
              $SEDCOMMAND 's/DISPLAY=//g')"
}

getXParameters()
{
  XAUTH_VAR=""
  DISP_VAR=""

  getDisplay
  getXCookie

  XPARAMETERS=""

  if [ "x$XAUTH_VAR" != "x" ] && [ "x$DISP_VAR" != "x" ];
  then
    XPARAMETERS="DISPLAY='$DISP_VAR' XAUTHORITY='$XAUTH_VAR'"
  fi
}

configureNxnetwork()
{
  if [ "x$XPARAMETERS" != "x" ];
  then
    DISPLAY="$DISP_VAR" XAUTHORITY="$XAUTH_VAR" NX_ROOT="${NX_VAR_DIR}/tmp" \
           NX_CONFIG="${NX_VAR_DIR}/tmp" HOME="${NX_VAR_DIR}/tmp" "${NX_ROOT}/bin/nxrunner" --setup
  else
    NX_ROOT="${NX_VAR_DIR}/tmp" NX_CONFIG="${NX_VAR_DIR}/tmp" \
           "${NX_ROOT}/bin/nxrunner" --setup
  fi
}

runPlayerConfigurator ()
{
  if [ "x${system}" != "xmacosx" ];
  then
    nxuser="0"
    nxgroup="0"

    nxuser_name="root"

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

      nxuser=$($IDCOMMAND -u ${SUDO_USER})
      nxuser_name="${SUDO_USER}"

    elif [ "x${PACKAGE_FILE}" != "x" ]
    then

      userid=$(${PSCOMMAND} aux | ${GREPCOMMAND} ${PACKAGE_FILE} | ${HEADCOMMAND} -n 1 | ${AWKCOMMAND} '{print $1}')
      nxuser_name=$(${AWKCOMMAND} -v val=${userid} -F ":" '$3==val{print $1}' /etc/passwd)

      if [ "x${nxuser_name}" != "x" ];
      then
        nxuser="${userid}"
      else
        printMsg "Cannot find owner of installer" "cmd"
      fi
    fi

   if [ "x${nxuser_name}" != "x" ];
   then
     nxgroup=$($IDCOMMAND -G ${nxuser_name} | ${AWKCOMMAND} '{print $1}')
   fi

   out=$( NX_USER="${nxuser}" NX_GROUP="${nxgroup}" "${NX_ROOT}/bin/nxplayer" --configurator > /dev/null 2>&1 &)
  fi
}

setEtcLink ()
{
  ETC_NXSERVER="/etc/NX/nxserver"

  if [ ! -h "$ETC_NXSERVER" ];
  then
    commandRm "$ETC_NXSERVER" "warn"
  fi

  if [ ! -f "$ETC_NXSERVER" ];
  then
    commandLn "${NX_ROOT}/bin/nxserver.app/Contents/MacOS/nxserver" "$ETC_NXSERVER" "error"
  fi
}

setWebReferrer ()
{
  "$SEDCOMMAND" "s/#WebReferrer/WebReferrer/" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

  commandRestoreFile "$CONFIG_FILE" "tmp"

  "$SEDCOMMAND" "s/#WebRedirect/WebRedirect/" "$CONFIG_FILE" > "$CONFIG_FILE.tmp"

  commandRestoreFile "$CONFIG_FILE" "tmp"
}

procedureInstallBasic ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    if [ "${system}" = "macosx" ];
    then
      if [ -f "${CONFIG_FILE}" ];
      then
        procedurePreuninstall "1"
      fi
    else
      getPackagePath "${PACKAGE_NAME}"
      if [ ${ret_getPackagePath} = 0 ];
      then
        if [ "x${ret_packagePath}" != "x${NX_ROOT}" ];
        then
          getProductName "${PACKAGE_NAME}"
          printMsg "${ret_getProductName} package is already installed in: ${ret_packagePath}"
          return 0
        fi
      else
        printMsg "Cannot read installation folder" "error"
        return 0
      fi
    fi

    if [ ! -f "${NX_ROOT}/etc/node.cfg" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
                      NX_POSTINST=1 "${NX_ROOT}/scripts/setup/nxnode" \
                      --install --basic
    fi

    if [ ! -f "${NX_ROOT}/etc/server.cfg" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
                      NX_POSTINST=1 "${NX_ROOT}/scripts/setup/nxserver" \
                      --install --basic
    fi

    NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
                    NX_POSTINST=1 "${NX_ROOT}/scripts/setup/nxrunner" \
                    --install-service

    return 0
  fi

  USER_NX="root"
  NX_POSTINST=1

  initializeOperation "install-basic"
  printOperationInfo "install-basic"

  if [ "${system}" = "macosx" ];
  then
    if [ -d "${NX_ROOT}/var" ];
    then
      commandCpDir "${NX_ROOT}/var" "${NX_VAR_DIR}/../"
      #commandRmDirRecursively "${NX_ROOT}/var"
    fi
  fi

  selinuxOperations
  checkETCDirectory

  setUserShell nx

  makeNXConfig
  makeNXConfigServer

  setConnectionMethods

  checkNXConfiguration
  upgradeLicenseFile

  printSummaryInfo "install-basic"

  exit 0
}

setIconForNxnode ()
{
  iconScript="$NX_ROOT/scripts/setup/iconScript.sh"

  "$ECHOCOMMAND" '#!/usr/bin/env python' > "$iconScript"
  "$ECHOCOMMAND" "import Cocoa" >> "$iconScript"
  "$ECHOCOMMAND" "import sys" >> "$iconScript"
  "$ECHOCOMMAND" "Cocoa.NSWorkspace.sharedWorkspace().setIcon_forFile_options_(Cocoa.NSImage.alloc().initWithContentsOfFile_(sys.argv[1].decode('utf-8')), sys.argv[2].decode('utf-8'), 0) or sys.exit(\"Unable to set file icon\")" >> "$iconScript"

  "$CHMODCOMMAND" "500" "$iconScript"

  "$iconScript" "$NX_ROOT/../Resources/application.icns" "$NXSHELL/../nxnode"

  "$RMCOMMAND" "$iconScript"
}

askForAccess ()
{
  #
  # Run nxserver during installation
  #  to force MacOS Accessibility window to pop-up.
  #  (MacOS 10.14 and newer).
  #

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

    getMacOSXVersion

    if ([ ${mac_ver_major} -eq 10 ] && [ ${mac_ver_minor} -ge 14 ]) || \
       [ ${mac_ver_major} -gt 10 ]
    then
      setIconForNxnode

      runCommand "'$NXSHELL' --installation-access-request" \
                 "Cannot run installation access request"
    fi
  fi
}

setEglCapture ()
{
  if [ "x${system}" != "xmacosx" ];
  then
    runCommand "'$NXSHELL' --eglcapture yes" \
               "Cannot set egl capture."
  fi
}

InstallVirtualGL ()
{
  if [ "x${system}" != "xmacosx" ];
  then
    "${NXSHELL}" --virtualglinstall > /dev/null 2>&1
  fi
}

UpgradeServerHistory ()
{
  if [ "${major_version}" -le "8" ];
  then
    runCommand "'$NXSHELL' --updatehistory" \
               "Cannot update nxserver history."
  fi
}

enterpriseEvalMsg()
{
  if [ "x${system}" != "xmacosx" ];
  then
    if [ ! -f "$LICENSE_FILE" ];
    then
        serverVersionFromAcronym "${NEW_LICENSE_ACRONYM}"
        printMsgNoDot "Your${NOMACHINE_EXTENSION} could not find"
        printMsgNoDot "any valid subscription. Activate your subscription or go to"
        printMsgNoDot "https://nomachine.com/enterprise/enterprise-evaluation"
        printMsgNoDot "to generate an evaluation license."
    else
      checkStr="$("${NXSHELL}" --subscription | "${GREPCOMMAND}" "subscription is outdated" || true)"

      if [ "x${checkStr}" != "x" ];
      then
        printMsgNoDot "Your evaluation subscription is outdated."
        printMsgNoDot "Activate a valid subscription or go to"
        printMsgNoDot "https://nomachine.com/enterprise/enterprise-evaluation"
        printMsgNoDot "to generate a new evaluation subscription."
      fi
    fi
  fi
}

procedureInstall ()
{
  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    if [ "${system}" = "macosx" ];
    then
      if [ -f "${CONFIG_FILE}" ];
      then
        procedurePreuninstall "1"
      fi
    else
      getPackagePath "${PACKAGE_NAME}"
      if [ ${ret_getPackagePath} = 0 ];
      then
        if [ "x${ret_packagePath}" != "x${NX_ROOT}" ];
        then
          getProductName "${PACKAGE_NAME}"
          printMsg "${ret_getProductName} package is already installed in: ${ret_packagePath}"
          return 0
        fi
      else
        printMsg "Cannot read installation folder" "error"
        return 0
      fi
    fi

    restoreContextForInstalationDir

    if [ "x${system}" = "xmacosx" ] && [ -f "${NX_ROOT}/share/mimetypes" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxrunner" \
                      --update ${SYSTEM}
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" \
                      --update ${SYSTEM}
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxrunner" \
                      --install ${SYSTEM}
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" \
                      --install ${SYSTEM}
    fi

    if [ -f "${NX_ROOT}/etc/node.cfg" ] && [ "x${NX_CHANGE_MODE}" != "x1" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
                      NX_CHANGE_MODE="${NX_CHANGE_MODE}" \
                      "${NX_ROOT}/scripts/setup/nxnode" --update ${SYSTEM}
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
      NX_CHANGE_MODE="${NX_CHANGE_MODE}" NEW_LICENSE_ACRONYM="$NEW_LICENSE_ACRONYM" \
                      "${NX_ROOT}/scripts/setup/nxnode" --install ${SYSTEM}
    fi

    updateMacOS="0"

    if [ -f "${NX_ROOT}/etc/server.cfg" ] && [ "x${NX_CHANGE_MODE}" != "x1" ];
    then
      updateMacOS="1"
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
                      NX_CHANGE_MODE="${NX_CHANGE_MODE}" \
                      "${NX_ROOT}/scripts/setup/nxserver" --update ${SYSTEM}
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
      NX_CHANGE_MODE="${NX_CHANGE_MODE}" NEW_LICENSE_ACRONYM="$NEW_LICENSE_ACRONYM" \
                      "${NX_ROOT}/scripts/setup/nxserver" --install ${SYSTEM}
    fi

    return 0
  fi

  initializeOperation "install"
  printOperationInfo "install"

  setCatalinaUpper

  isAnywhereAvailable
  removeObsoleteMenuApplications

  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$system" = "xmacosx" ];
  then
    commandRmIfExist "${NX_ROOT}/etc/nxserver.md5" "cmd"

    commandRmIfExist "${NX_ROOT}/etc/nxnode.md5" "cmd"

    unloadPlist

    commandRmIfExist "/Library/LaunchAgents/com.nomachine.localnxserver.plist" "cmd"

    if [ "x$catalinaUpper" = "x1" ];
    then

      setEtcLink

    fi
  fi

  selinuxOperations

  checkETCDirectory

  if [ "x${NX_POSTINST}" != "x1" ];
  then
    makeNXConfig
  fi

  setConnectionMethods
  setSystemLogFileKey
  setConnectPolicyKey

  setShell
  genNXUsersKeys

  if [ "x${NX_POSTINST}" != "x1" ];
  then
    makeNXConfigServer
  fi

  if [ "x${NX_POSTINST}" != "x1" ];
  then
    checkNXConfiguration
    upgradeLicenseFile
  fi

  setCommandSessregKey
  setNxsessregPermisions
  setFail2banPermisions
  setNxUserMngshPermissions
  createServerLogFile

  addNXinit

  setAvailableSessionKey
  setSSHClientKey

  runCommand "'${NXSHELL}' --addtoredis" "Cannot add installation data to database"

  createNxdCert

  addVGL

  installPolicyFiles
  installResources

  setPermissionsNXHome

  setSSHAuthorizedKeysValue

  setPhysicalDesktopSharing

  setWebReferrer

  #
  # Enabling webplayer everywhere except NoMachine free,
  # Enterprise Desktop and Terminal Server Node"
  #

  isSupportedHtd

  if [ "x${ret_isSupportedHtd}" = "x1" ];
  then
    if [ -f "${HTD_USR_CONFIG_FILE}" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
                      "${NX_ROOT}/scripts/setup/nxwebplayer" --update ${SYSTEM}
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" \
                      "${NX_ROOT}/scripts/setup/nxwebplayer" --install ${SYSTEM}
    fi

    if [ "x$system" = "xmacosx" ];
    then
      getMacOSXVersion

      if [ "$mac_ver_major" -ge "11" ];
      then
        /usr/bin/defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array nx nxhtd
      fi
    fi
  fi

  setSELinuxContextForLogs

  restoreContextForInstalationDir

  restoreContextForDir "${NX_VAR_DIR}"

  restoreContextForDir "${NX_ETC_DIR}"

  upgradeRemoteNodeFrom3

  if [ "x$catalinaUpper" = "x1" ];
  then

    commandRegisterApp "${NX_ROOT}/bin/nxserver.app" "error"

    runCommand "tccutil reset Accessibility com.nomachine.nxnode" "Remove nxnode form Accessibility" "warn"

  fi

  setEglCapture

  startNXServer

  if [ "x$catalinaUpper" = "x1" ];
  then

    commandRegisterApp "${NX_ROOT}/bin/nxserver.app" "error"

  fi

  if [ "x$catalinaUpper" = "x0" ];
  then
    askForAccess
  fi

  printSummaryInfo "install"

  enterpriseEvalMsg
  
  exit 0
}

package_files=(
/bin/nxserver
/bin/nxserver.bin
/bin/nxhtd
/bin/nxhtd.bin
/bin/nxkeygen
/bin/nxdb
/etc/server.lic.sample
/etc/server-debian.cfg.sample
/etc/server-fedora.cfg.sample
/etc/server-mandriva.cfg.sample
/etc/server-redhat.cfg.sample
/etc/server-suse.cfg.sample
/etc/server-slackware.cfg.sample
/etc/server-solaris.cfg.sample
/etc/server-macosx.cfg.sample
/etc/stop-server
/etc/sshstatus
/scripts/etc/localhost/server.cfg
/scripts/etc/nxserver
/scripts/etc/pam.d/nx-login
/scripts/init/nx.sh
/scripts/init/nx.csh
/scripts/init/nxserver
/scripts/init/nxserver.conf
/scripts/systemd/${SYSTEMD_SERVER_SERVICE}
/scripts/restricted/nxcat.sh
/scripts/restricted/nxlsof.sh
/scripts/restricted/nxchown.sh
/scripts/restricted/nxhtdchown.sh
/scripts/restricted/nxeglevent.sh
/scripts/restricted/nxwebhostcertget.sh
/scripts/restricted/nxsshhostcertget.sh
/scripts/restricted/nxsshhostcertset.sh
/scripts/restricted/nxsshhostcertrestore.sh
/scripts/restricted/nxfwadd.sh
/scripts/restricted/nxfwdel.sh
/scripts/restricted/nxfwget.sh
/scripts/restricted/nxclustermaster.sh
/scripts/restricted/nxstandby.sh
/scripts/restricted/nxsynchronize.sh
/scripts/restricted/nxclusterslave.sh
/scripts/restricted/nxdebugcollect.sh
/scripts/restricted/nxgroupadd.sh
/scripts/restricted/nxpasswd.sh
/scripts/restricted/nxpasswdask.sh
/scripts/restricted/nxshutdown.sh
/scripts/restricted/nxlaunchctl.sh
/scripts/restricted/nxquotaadd.sh
/scripts/restricted/nxwtmpadd.sh
/scripts/restricted/nxwtmpdel.sh
/scripts/restricted/nxhost.sh
/scripts/restricted/nxhtd.sh
/scripts/restricted/nxhtdroot.sh
/scripts/restricted/nxgfxcheck.sh
/scripts/restricted/nxrestart.sh
/scripts/restricted/nxchmod.sh
/scripts/restricted/nxrenice.sh
/scripts/restricted/nxsetsshagent.sh
/scripts/restricted/nxdbusmonitor.sh
/scripts/restricted/nxroutein.sh
/scripts/restricted/nxrouteinadd.sh
/scripts/restricted/nxrouteindel.sh
/scripts/restricted/nxdisableservices.sh
/scripts/restricted/nxenableservices.sh
/scripts/restricted/nxsshrestart.sh
/scripts/vgl/vglrun
/scripts/vgl/librrfaker.so
/scripts/vgl/libvglfaker.so
/scripts/vgl/libgefaker.so
/scripts/vgl/libdlfaker.so
/scripts/vgl/libGL.so
/scripts/vgl/vglserver_config
/scripts/vgl/vglgenkey
/scripts/nxpasswdask.sh
/scripts/lb/nxweightedroundrobin.pl
/scripts/setup/nxserver
/share/mac/launchd/com.nomachine.server.plist
/share/policy/org.freedesktop.pkexec.nomachine.policy
/share/policy/org.freedesktop.packagekit.policy
/share/policy/org.freedesktop.color.policy
/etc/administrators.db.lock
/etc/administrators.db.sample
/etc/guests.db.lock
/etc/guests.db.sample
/etc/passwords.db.lock
/etc/passwords.db.sample
/etc/node-groups.db.lock
/etc/node-groups.db.sample
/etc/server-groups.db.lock
/etc/server-groups.db.sample
/etc/logrotate.db.lock
/etc/logrotate.db.sample
/etc/profiles.db.lock
/etc/profiles.db.sample
/etc/users.db.lock
/etc/users.db.sample
/etc/usb.db.lock
/etc/usb.db.sample
/etc/nodes.db.lock
/etc/hosts.db.lock
/etc/groups.db.lock
/etc/network.db.lock
/etc/network.db.sample
/etc/keys/host/ht_host_rsa_key.crt
/etc/keys/host/ht_host_rsa_key
/etc/keys/host/nx_host_rsa_key.crt
/etc/keys/host/nx_host_rsa_key
/etc/web.cfg.sample
/etc/magic
/etc/mime.types
/share/documents/server/install-notices
/share/documents/server/license-info
/share/documents/server/credits.txt
/share/documents/server/readme-info
/share/documents/server/update-notices
/share/htdocs/index.html
/share/htdocs/favicon.ico
/share/htdocs/redirect.html
/share/htdocs/nx_web_player.png
/share/htdocs/oops.png
/share/htdocs/title_bg.png
/share/htdocs/logo.png
/share/htdocs/404.png
/lib/libav.so
/lib/perl/DBI.so
/lib/perl/GD.so
/lib/perl/SQLite.so
/lib/perl/Tty.so
/lib/perl/libgd.so
)

package_directories_empty=(
/bin
/scripts/etc/localhost
/scripts/etc
/scripts/init
/scripts/systemd
/scripts/restricted
/scripts/setup
/scripts/lb
/scripts/vgl
/scripts
/share/documents/guides
/share/documents/server
/share/documents
/share/config
/share/htdocs
/share/applnk/server/Linux/xdg
/share/applnk/server/Linux
/share/applnk/server/Solaris
/share/applnk/server
/share/applnk
/share/policy
/lib/perl
/lib
)

package_directories_recursive=(
/share/documents/server
/lib/perl/nxserver
/lib/perl
)


processes_to_kill=(
nxserver.bin
nxserver
nxhtd.bin
nxhtd
#nxstat.bin
#nxstat
nxkeygen
)

removeSSHSupport3 ()
{

  #
  # Removing only DSA key from NX 3
  # Only update procedure.
  #

  if [ -f "${currentDSAKey}" ];
  then
    commandBackupMvFile "${currentDSAKey}" "backup" "error"
  fi

  setConnectionMethods
}

procedureFinalUninstall ()
{
  commandRmIfExist "/etc/profile.d/nx.sh" "cmd"
  commandRmIfExist "/etc/profile.d/nx.csh" "cmd"

  if [ "x${NX_CHANGE_MODE}" = "x1" ];
  then
    return 0
  fi

  if [ "x${system}" = "xmacosx" ];
  then
    commandRmDirRecursively "${NX_ROOT}/bin/nxrunner.app" "cmd"
    commandRmDirIfExistEmpty "${NX_ROOT}/bin" "cmd"

    commandRm "${NX_ROOT}/share/mac/launchd/com.nomachine.nxd.plist" "cmd"
    commandRm "${NX_ROOT}/share/mac/launchd/com.nomachine.nxd.plist.sockets" "cmd"
    commandRm "${NX_ROOT}/share/mac/launchd/com.nomachine.nxd.plist.sockets.README" "cmd"
    commandRm "${NX_ROOT}/share/mac/launchd/com.nomachine.nxhtd.plist" "cmd"

    commandRmIfExist "/etc/NX/player/localhost/player.cfg" "cmd"
    commandRmDirIfExistEmpty "/etc/NX/player/localhost" "cmd"
    commandRmDirIfExistEmpty "/etc/NX/player" "cmd"
    commandRmDirIfExistEmpty "/etc/NX" "cmd"

    commandRmFiles "/var/db/receipts/com.nomachine." "cmd"
    commandRmDirRecursively "${NX_ROOT}/lib" "cmd"

    #
    # for old versions (<=10.5)
    #

    commandRmDirRecursively "/Library/Receipts/nxrunner-${VERSION}-cc.pkg" "cmd"
    commandRmDirRecursively "/Library/Receipts/nxplayer-${VERSION}-cp.pkg" "cmd"
    commandRmDirRecursively "/Library/Receipts/nxnode-${VERSION}-csen.pkg" "cmd"
    commandRmDirRecursively "/Library/Receipts/nxserver-${VERSION}-cs.pkg" "cmd"
    commandRmDirRecursively "/Library/Receipts/nxwebplayer-${VERSION}-cw.pkg" "cmd"
  fi
}

backupAuthorizedKeyFileUninstall ()
{
  isInstalledMacPkg "node"
  if [ ${ret_isInstalledMacPkg} = 0 ];
  then
    return 0
  fi

  if [ -f "${FILE_AUTHORIZED_KEYS}" ];
  then
    #command="${GREPCOMMAND} 'NoMachine.*Service' '${FILE_AUTHORIZED_KEYS}'"
    command="${GREPCOMMAND} 'NoMachine' '${FILE_AUTHORIZED_KEYS}'"
    outCommand=$(${BASHSHELL} -c "${command}" 2>&1)
    if [ "x${outCommand}" != "x" ];
    then
      #${SEDCOMMAND} -e '/NoMachine.*Service/d' "${FILE_AUTHORIZED_KEYS}" > "${FILE_AUTHORIZED_KEYS}".uninstall
      ${SEDCOMMAND} -e '/NoMachine/d' "${FILE_AUTHORIZED_KEYS}" > "${FILE_AUTHORIZED_KEYS}".uninstall
    fi
  fi
}

restoreAuthorizedKeyFileUninstall ()
{
  if [ -f "${NXHOME}/.ssh/authorized_keys.uninstall" ];
  then
    commandMv "${NXHOME}/.ssh/authorized_keys.uninstall" "${NXHOME}/.ssh/authorized_keys" "warn"
  elif [ -f "${NXHOME}/.ssh/authorized_keys2.uninstall" ];
  then
    commandMv "${NXHOME}/.ssh/authorized_keys2.uninstall" "${NXHOME}/.ssh/authorized_keys2" "warn"
  fi

  commandRm "${currentDSAKey}" "warn"
  commandRm "${originalDSAKey}" "warn"

  commandRm "${currentRSAKey}" "warn"
  commandRm "${originalRSAKey}" "warn"
}

resetSupportForEGL ()
{
  runCommand "$NXSHELL --eglcapture no" "Cannot disable egl capture" "cmd"
}

UninstallVirtualGL ()
{
  if [ "x${system}" != "xmacosx" ];
  then
    "${NXSHELL}" --virtualgluninstall > /dev/null 2>&1
  fi
}

SubscriptionRemove ()
{
  if [ "x${system}" != "xmacosx" ];
  then
    runCommand "$NXSHELL --subscriptionremove" "Cannot remove subscription" "cmd"
  fi
}

removeShellDesktop ()
{
  directories=(
    "/usr/share/applications"
    "/usr/lib/systemd/user"
    "/usr/bin"
    "/usr/libexec"
    "/usr/lib"
    "/usr/lib/x86_64-linux-gnu/libexec"
    "/usr/lib64/libexec"
  )

  for dir in "${directories[@]}"; do
    if ls "${dir}"/*.backup.NX 1> /dev/null 2>&1; then
      rm -rf "${dir}"/*.backup.NX
    fi
  done
}

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
        if [ "x${system}" = "xmacosx" ];
        then
          backupAuthorizedKeyFileUninstall
        fi

        if [ -f "${NX_ETC_WEBPLAYER}" ] || [ -f "${HTD_USR_CONFIG_FILE}" ] || [ -f "${HTD_USR_CONFIG_FILE}.sample" ];
        then
          NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxwebplayer" --uninstall
        fi

        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxserver" --uninstall
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxnode" --uninstall
        NX_MPKG_PACKAGE="${PACKAGE_NAME}" "${NX_ROOT}/scripts/setup/nxplayer" --uninstall
        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"
  printOperationInfo "uninstall"

  shutdownServer
  UninstallVirtualGL
  resetSupportForEGL
  SubscriptionRemove

  if [ -f "${NX_ROOT}/etc/users.id_dsa" ];
  then
    printMsgNoDot "The NoMachine setup program found that the NoMachine Server package was installed on the machine"
    printMsgNoDot "but the update procedure was never executed. To be able to successfully uninstall"
    printMsgNoDot "the NoMachine Server, you will need to run the 'nxsetup --update' procedure first, and"
    printMsg "'nxserver --uninstall' afterward"

    exit 1
  fi

  resetPermissionsServer
  archiveNXUsersKeys
  resetNXConfigServer
  removeNXinit
  removeETCDirectory
  removeNxhtdDaemonFileApple
  uninstallPolicyFiles
  removeShellDesktop

  #
  # Removing nxserver.conf file added by function addNXserverConf
  #

  if [ -f /etc/init/nxserver.conf ]; then
    ${RMCOMMAND} "/etc/init/nxserver.conf"
  fi

  uninstallResources

  procedureFinalUninstall
  printSummaryInfo "uninstall"

  exit 0
}

#####################################################################################
############################# SELinux Functions #####################################
#####################################################################################

setContextForAuthKeys ()
{
  setSELinuxStatus

  non_default_key="${1}"

  if [ ${SELINUX_ENABLED} = 1 ];
  then
    if [ -f "${non_default_key}" ];
    then
      setSELinuxContext "user_home_t" "${non_default_key}"
    elif [ -f "${FILE_AUTHORIZED_KEYS}" ];
    then
      setSELinuxContext "user_home_t" "${FILE_AUTHORIZED_KEYS}"
    fi

    if [ -f "${currentDSAKey}" ];
    then
      setSELinuxContext "user_home_t" "${currentDSAKey}"
    fi

    if [ -f "${originalDSAKey}" ];
    then
      setSELinuxContext "user_home_t" "${originalDSAKey}"
    fi

    if [ -f "${currentRSAKey}" ];
    then
      setSELinuxContext "user_home_t" "${currentRSAKey}"
    fi

    if [ -f "${originalRSAKey}" ];
    then
      setSELinuxContext "user_home_t" "${originalRSAKey}"
    fi

    if [ -d "${NXUSERHOME}" ];
    then
      restoreContextForDir "${NXUSERHOME}"
    fi
  fi
}

setContextForServerShell ()
{
  setSELinuxStatus

  if [ ${SELINUX_ENABLED} = 1 ];
  then
    setSELinuxContext "shell_exec_t" "${NXSHELL}"
  fi
}

selinux_execstack_files=(
/bin/nxserver.bin
/bin/nxhtd.bin
)

selinuxOperations()
{
  setSELinuxStatus

  if [ ${SELINUX_ENABLED} = 1 ];
  then
    setContextForServerShell
    setSELinuxExecStack

    setSELinuxContext "shell_exec_t" "${NX_ROOT}/bin/nxserver"
  fi
}

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

procedureUpdate()
{
  if [ "$#" = 1 ];
  then
    if [ "${1}"x = "auto"x ];
    then
      updateType="auto"
    else
      updateType=""
    fi
  fi

  if [ "x${NX_MPKG_PACKAGE}" = "x" ];
  then
    if [ "${system}" = "macosx" ];
    then
      if [ -f "${CONFIG_FILE}" ];
      then
        if [ "${updateType}"x = "auto"x ] || [ "${UPDATETYPE}"x = "auto"x ];
        then
          procedurePreuninstall "1" "auto"
        else
          procedurePreuninstall "1"
        fi
      fi
    else
      getPackagePath "${PACKAGE_NAME}"
      if [ ${ret_getPackagePath} = 0 ];
      then
        if [ "x${ret_packagePath}" != "x${NX_ROOT}" ];
        then
          getProductName "${PACKAGE_NAME}"
          printMsg "${ret_getProductName} package is already installed in: ${ret_packagePath}"
          return 0
        fi
      else
        printMsg "Cannot read installation folder" "error"
        return 0
      fi
    fi

    restoreContextForInstalationDir

    NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxrunner" --update ${SYSTEM}
    NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxplayer" --update ${SYSTEM}

    if [ -f "${NX_ROOT}/etc/node.cfg" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxnode" --update ${SYSTEM}
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" "${NX_ROOT}/scripts/setup/nxnode" --install ${SYSTEM}
    fi

    if [ -f "${NX_ROOT}/etc/server.cfg" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxserver" --update ${SYSTEM}
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" "${NX_ROOT}/scripts/setup/nxserver" --install ${SYSTEM}
    fi

    return 0
  fi

  initializeOperation "update"
  printOperationInfo "update" "${upgrade}"

  #
  # Remove not needed anymore nxnode.app.
  #

  if [ -d "${NX_ROOT}/bin/nxnode.app" ] && [ "x$system" = "xmacosx" ];
  then
    "${RMCOMMAND}" -rf "${NX_ROOT}/bin/nxnode.app"
  fi

  setCatalinaUpper
  isAnywhereAvailable

  if [ "x${UPDATETYPE}" = "xauto" ] &&
     [ -f "${NX_ROOT}/nomachine_automatic_update.deb" ] &&
     [ -f "${NX_ROOT}/nomachine_automatic_update.rpm" ];
  then
    installIncreaseVersionPackage
  fi

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

    unloadPlist

    commandRmIfExist "/Library/LaunchAgents/com.nomachine.localnxserver.plist" "cmd"

    if [ "x$catalinaUpper" = "x1" ];
    then
      setEtcLink
    fi
  fi

  genNXUsersRSAKeys

  selinuxOperations

  if [ "x${upgrade}" != "x1" ];
  then
    if [ "${UPDATETYPE}"x != "auto"x ];
    then
      shutdownServer
    fi

    if [ -f "${NX_VAR_DIR}/run/server.pid.lock" ]
    then
      commandChown "nx" "${NX_VAR_DIR}/run/server.pid.lock"
    fi

    if [ "${system}" = "macosx" ];
    then
      commandRmIfExist "${NX_VAR_DIR}/run/server.pid.lock" "cmd"
      removeNxdDaemonFileApple
    fi
  else
    restoreUsersDB
  fi

  if [ "x$anywhere" = "x1" ];
  then
    removeObsoleteMenuApplications
  fi

  renameLog "audit.log";
  renameLog "daemon.log";
  renameLog "error.log";
  renameLog "server.log";
  renameLog "service.log";

  makeConfBackup
  checkETCDirectory
  makeNXConfig
  updateNXConfigServer

  updateConfigFile
  reconfigureUPnPKey

  if [ "x${upgrade}" = "x1" ];
  then
    setAvailableSessionKey
  fi
  checkAvailableSessionTypes

  setUserShell nx

  fixoldkeyfile
  checkNXConfiguration
  checkNXkeys
  createServerLogFile
  resetSSHMethod
  upgradeLicenseFile
  setSSHClientKey
  removeNXinit

  if [[ "${UPDATETYPE}x" = "autox" ]]; then
    addNXinit "auto"
  else
    addNXinit
  fi

  setSystemLogFileKey
  setConnectPolicyKey
  copySessionHistory
  checkSessregPath
  setNxsessregPermisions
  setFail2banPermisions
  setNxUserMngshPermissions

  cleanShareDirectory

  upgradeMultinodeServerFrom3

  setUpRedis
  UpgradeServerHistory

  removeOrphansServers

  createNxdCert

  installResources
  installPolicyFiles
  addVGL

  setPhysicalDesktopSharing

  isSupportedHtd

  if [ "x${ret_isSupportedHtd}" = "x1" ];
  then
    if [ -f "${HTD_USR_CONFIG_FILE}" ] || [ -f "${NX_ROOT}/etc/htd.cfg" ];
    then
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" UPDATETYPE="${updateType}" "${NX_ROOT}/scripts/setup/nxwebplayer" --update ${SYSTEM}
    else
      NX_MPKG_PACKAGE="${PACKAGE_NAME}" PACKAGE_TYPE="${PACKAGE_TYPE}" "${NX_ROOT}/scripts/setup/nxwebplayer" --install ${SYSTEM}
    fi

    if [ "x$system" = "xmacosx" ];
    then
      getMacOSXVersion

      if [ "$mac_ver_major" -ge "11" ];
      then
        /usr/bin/defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array nx nxhtd
      fi
    fi
  fi

  if [ "x$catalinaUpper" = "x1" ];
  then
    commandRegisterApp "${NX_ROOT}/bin/nxserver.app" "error"
  fi

  enterpriseEvalMsg

  #if [ "${UPDATETYPE}"x != "auto"x ];
  #then
  #  checkStr=$("${NXSHELL}" --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" "warnshow"
  #    printMsgNoDot "install a new version of the software, please visit the" "warnshow"
  #    printMsgNoDot "NoMachine Web site at http://www.nomachine.com/" "warnshow"
  #    printMsgNoDot "to acquire a valid subscription." "warnshow"

  #    exit 1
  #  fi
  #fi

  if [ "x$system" = "xmacosx" ];
  then
    commandRmIfExist "${NX_ROOT}/etc/nxserver.md5" "cmd"

    commandRmIfExist "${NX_ROOT}/etc/nxnode.md5" "cmd"
  fi

  if [ "${UPDATETYPE}"x != "auto"x ];
  then
    if [ "x${upgrade}" = "x1" ];
    then
      shutdownServer
    fi
    startNXServer
  fi

  if [ "x$catalinaUpper" = "x0" ];
  then
    askForAccess
  fi

  rmPreviousVersion
  
  printSummaryInfo "update"

  exit 0
}

procedurePreuninstall ()
{
  noexit="$1"

  initializeOperation "preuninstall"
  printOperationInfo "preuninstall"

  checkServerInstallation
  if [ ${ret_checkServerInstallation} = 0 ];
  then
    printMsg "Shutting down: nxserver"

    if [ "${2}"x != "auto"x ];
    then
      shutdownServer
    fi

    cleanNXDb
    printMsg "Cleaned up NoMachine session DB"
  fi

  printSummaryInfo "preuninstall"

  if [ "x${noexit}" = "x1" ];
  then
    return 0
  else
    exit 0
  fi
}

procedurePostUpgrade ()
{
  SLEEP_TIME=1
  PM_PID=$1

  LOGFILE="${UPDATELOG}"
  PROCESS="${UPDATE}"

  if [ "x${PM_PID}" = "x" ];
  then
    return
  fi

  canRecover=0

  while [ ${canRecover} = 0 ];
  do
    ps_out=$(${PSCOMAMND} a -o pid | ${AWKCOMMAND} '{print $1}' | ${GREPCOMMAND} "^${PM_PID}$" 2>&1)

    if [ "x${ps_out}" = "x" ];
    then
      canRecover=1
    else
      ${SLEEPCOMMAND} ${SLEEP_TIME}
    fi
  done

  startNXServer

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

procedureprintbrandmessages ()
{
  if [ -f "${NX_ROOT}/share/branding/server/branding.db" ];
  then
    licenceInfo=$(${HEADCOMMAND} -n 1 "${NX_ROOT}/share/branding/server/branding.db" 2>&1)
    prev=""

    for line in 1 2 3 4 5 6 7 8 9 10;
    do
      txt=""
      txt=$(${PRINTFCOMMAND} "${licenceInfo}" | ${HEADCOMMAND} -n ${line} | ${TAILCOMMAND} -n 1)
      if [ "x${txt}" != "x" -a "x${prev}" != "x${txt}" ];
      then
        ${ECHOCOMMAND} "${txt}"
        prev=${txt}
      else
        break
      fi
    done
  fi

  if [ -f "${NX_ROOT}/share/branding/server/branding.db" ];
  then
    licenceInfo=$(${HEADCOMMAND} -n 6 "${NX_ROOT}/share/branding/server/branding.db" 2>&1 | ${TAILCOMMAND} -n 1)
    prev=""

    for line in 1 2 3 4 5 6 7 8 9 10;
    do
      txt=""
      txt=$(${PRINTFCOMMAND} "${licenceInfo}" | ${HEADCOMMAND} -n ${line} | ${TAILCOMMAND} -n 1)

      if [ "x${txt}" != "x" -a "x${prev}" != "x${txt}" ];
      then
        ${ECHOCOMMAND} "${txt}"
        prev=$txt
      else
        break
      fi
    done
  fi
}

procedureRotateBackupAuthKey ()
{
  ret_procedureRotateBackupAuthKey=0

  #
  # 1 - rotate old keys
  # 0 - replace old backup key
  #

  ROTATE_BACKUP_FILE=1
  MAX_ROTATED_FILES=5

  current="${1}"

  backup="${current}.backup"

  if [ -f "${current}" ];
  then

    if [ -f "${backup}" ];
    then

      printMsg "Saving current key in file:"
      printMsg "${backup}"

      #
      # File ${backup} already exist
      #

      if [ ${ROTATE_BACKUP_FILE} == 1 ] && [ ${MAX_ROTATED_FILES} -gt 0 ];
      then

        x=${MAX_ROTATED_FILES}
        prev_x=""

        while [ ${x} -ge 1 ];
        do
          if [ ${x} -ge 2 ];
          then
            prev_x=$(${EXPRCOMMAND} ${x} - 1)
          else
            prev_x=""
          fi

          if [ -f "${backup}${prev_x}" ];
          then
            commandCp "${backup}${prev_x}" "${backup}${x}" "warn"
          fi

          x=$(${EXPRCOMMAND} $x - 1)
        done

        runShCommand "${CPCOMMAND} -fp '${current}' '${backup}'"

      else

        #
        # No rotating
        #

        runShCommand "${CPCOMMAND} -fp '${current}' '${backup}'"
      fi

    else
      runShCommand "${CPCOMMAND} -p '${current}' '${backup}'"
    fi

  else

    #
    # Auth Key does not exists in system
    # Do nothing.
    #

    ret_procedureRotateBackupAuthKey=1

    return 0
  fi

  return 0
}

procedureRestoreOriAuthKey ()
{
  #
  # Old name: procedureRestoreOrgDSAKey
  #
  # ${1} - current
  # ${2} - original
  #

  current="${1}"
  original="${2}"

  if [ -f "${FILE_AUTHORIZED_KEYS}" ];
  then
    stopped="yes"

    stopNXServer
    startNXServer

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

  if [ ! -f "${original}" ];
  then

    printMsg "Original ${2} key is not present in your system"
    printMsg "Try to reinstall the server package"

    if [ "x${stopped}" = "xyes" ];
    then

      startNXServer

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

    procedureRotateBackupAuthKey "${current}"

    #
    # Overwritting the current key by original.
    #

    printMsg "Restoring original key"
    commandCp "${original}" "${current}" "warn"

    printMsg "Completed"
  fi

  if [ "x${stopped}" = "xyes" ];
  then

    startNXServer

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

  return 0
}


getNXServerStatus ()
{
  retNXServerRunning=0
  retNXServerStopped=1
  retNXServerUnknown=2
  ret_getNXServerStatus=${retNXServerUnknown}

  InfoNXServerStopped="Service: nxserver disabled"
  InfoNXServerRunning="Service: nxserver enabled"
  InfoNXServerAlreadyRunning="Service already running"

  ret=$("${NXSHELL}" --status < /dev/null 2>&1)
  result_msg=$(${ECHOCOMMAND} "${ret}" | ${GREPCOMMAND} "${InfoNXServerRunning}")

  if [ "x${result_msg}" = "x" ];
  then
    result_msg=$(${ECHOCOMMAND} "${ret}" | ${GREPCOMMAND} "${InfoNXServerAlreadyRunning}")

    if [ "x${result_msg}" != "x" ];
    then
      ret_getNXServerStatus=${retNXServerRunning}
      return 0
    fi

    result_msg=$(${ECHOCOMMAND} "$ret" | ${GREPCOMMAND} "$InfoNXServerStopped")

    if [ "x$result_msg" = "x" ];
    then
      ret_getNXServerStatus=$retNXServerUnknown

      return 0
    else
      ret_getNXServerStatus=$retNXServerStopped

      return 0
    fi

  else
    ret_getNXServerStatus=$retNXServerRunning
    return 0
  fi
}

setAuthorizedKeyFile ()
{
  #
  # Function used especially for installation
  # after uninstallation without removing /usr/NX/ directory.
  #

  authkey_file="$1"

  isSSHSupported

  if [ "x${ret_isSSHSupported}" = "x1" ] && [ ! -f "${authkey_file}" ]\
     && [ "x${authkey_file}" != "x" ];
  then
    commandCp "${currentRSAKey}" "${authkey_file}" "onlylog"
    ${CATCOMMAND} "${currentDSAKey}" >> "${authkey_file}"

    commandChown "${USER_NX}" "${authkey_file}" "warn"
  fi

  setContextForAuthKeys
}

checkAuthorizedKeyFileName ()
{
  authkey_file="$1"

  ret_checkAuthorizedKeyFileName=0

  if [ ! -f "${authkey_file}" ];
  then
    commandCp "${currentRSAKey}" "${authkey_file}" "onlylog"
    ${CATCOMMAND} "${currentDSAKey}" >> "${authkey_file}"

    commandChown "${USER_NX}" "${authkey_file}" "warn"
  fi

  setContextForAuthKeys

  isSSHSupported

  if [ "x${ret_startNXServer}" != "x0" ] || [ "x${ret_isSSHSupported}" = "x0" ];
  then
    commandRm "${authkey_file}"
    commandRm "${NXHOME}/.ssh/node.localhost.id_dsa.pub.tmp"
    commandRm "${NXHOME}/.ssh/node.localhost.id_rsa.pub.tmp"

    ret_checkAuthorizedKeyFileName=1

    return 0
  fi

  ret_checkAuthorizedKeyFileName=0

  return 0
}

checkAuthorizedKeyFiles ()
{
  ret_checkAuthorizedKeyFiles=0
  ret_AuthorizedKeyFile=""

  if [ "x${FILE_AUTHORIZED_KEYS}" = "x" ];
  then
    readAuthorizedFileKey
  fi

  if [ -f "${NXHOME}/.ssh/authorized_keys2" ] && [ "x${FILE_AUTHORIZED_KEYS}" != "x${NXHOME}/.ssh/authorized_keys2" ];
  then
    akf2=1
    commandBackupMvFile "${NXHOME}/.ssh/authorized_keys2" "test" "error"
  fi

  if [ -f "${NXHOME}/.ssh/authorized_keys" ] && [ "x${FILE_AUTHORIZED_KEYS}" != "x${NXHOME}/.ssh/authorized_keys" ];
  then
    akf=1
    commandBackupMvFile "${NXHOME}/.ssh/authorized_keys" "test" "error"
  fi

  if [ "x${FILE_AUTHORIZED_KEYS_ENABLED}" = "x1" ];
  then
    checkAuthorizedKeyFileName "${FILE_AUTHORIZED_KEYS}"
    if [ ${ret_checkAuthorizedKeyFileName} = 0 ];
    then
      ret_AuthorizedKeyFile="${FILE_AUTHORIZED_KEYS}"
      ret_checkAuthorizedKeyFiles=0
      return 0
    fi
  fi

    if [ -f "${NXHOME}/.ssh/authorized_keys2.test" ];
    then
      commandCp "${NXHOME}/.ssh/authorized_keys2.test" "${NXHOME}/.ssh/authorized_keys2" "error"
    fi

   setValueAtCfgFile "${CONFIG_FILE}" "SSHAuthorizedKeys" "authorized_keys2"
   if [ ${ret_setValueAtCfgFile} = 0 ];
   then
     printMsg "Cannot update key: SSHAuthorizedKeys" "error"
   fi

    checkAuthorizedKeyFileName "${NXHOME}/.ssh/authorized_keys2"
    if [ ${ret_checkAuthorizedKeyFileName} = 0 ];
    then
      commandRmIfExist "${NXHOME}/.ssh/authorized_keys.test" "error"
      commandRmIfExist "${NXHOME}/.ssh/authorized_keys2.test" "error"

      ret_AuthorizedKeyFile="${NXHOME}/.ssh/authorized_keys2"
      ret_checkAuthorizedKeyFiles=0

      return 0
    else
      if [ "x$akf2" = "x" ];
      then
        commandRmIfExist "${NXHOME}/.ssh/authorized_keys2" "error"
      else
        commandBackupMvFile "${NXHOME}/.ssh/authorized_keys2" "bkp" "error"
      fi
    fi

    if [ -f "${NXHOME}/.ssh/authorized_keys.test" ];
    then
      commandCp "${NXHOME}/.ssh/authorized_keys.test" "${NXHOME}/.ssh/authorized_keys" "error"
    fi

    setValueAtCfgFile "${CONFIG_FILE}" "SSHAuthorizedKeys" "authorized_keys"
    if [ ${ret_setValueAtCfgFile} = 0 ];
    then
      printMsg "Cannot update key: SSHAuthorizedKeys" "error"
    fi

    checkAuthorizedKeyFileName "${NXHOME}/.ssh/authorized_keys"
    commandRmIfExist "${NXHOME}/.ssh/authorized_keys.test" "error"

    if [ ${ret_checkAuthorizedKeyFileName} = 0 ];
    then
      commandRmIfExist "${NXHOME}/.ssh/authorized_keys.test" "error"
      commandRmIfExist "${NXHOME}/.ssh/authorized_keys2.test" "error"

      ret_AuthorizedKeyFile="${NXHOME}/.ssh/authorized_keys"
      ret_checkAuthorizedKeyFiles=0

      return 0
    else
      if [ "x${akf}" = "x" ];
      then
        commandRmIfExist "${NXHOME}/.ssh/authorized_keys" "error"
      else
        commandBackupMvFile "${NXHOME}/.ssh/authorized_keys" "bkp" "error"
      fi
    fi

  ret_checkAuthorizedKeyFiles=1
  return 0
}

setAuthorizedKeyFileName ()
{
  ret_setAuthorizedKeyFileName=0

  updatePathinAuthKey "${currentRSAKey}"
  updatePathinAuthKey "${currentDSAKey}"

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

    #
    # SSHAuthorizedKeys already enabled
    #

    return 0
  fi

  checkAuthorizedKeyFiles

  if [ ${ret_checkAuthorizedKeyFiles} != 0 ];
  then

    if [ "x${NX_INSTALL_SILENT}" != "x1" ];
    then
      printMsg "Cannot determine authorized_key filename" "cmd"
      removeConnectionMethod "SSH"

      startNXServer "1"
    fi

    ret_setAuthorizedKeyFileName=1
    return 0
  fi

  akf=$(basename ${ret_AuthorizedKeyFile} 2>/dev/null)

  ${SEDCOMMAND} -e 's|^ *[#] *SSHAuthorizedKeys \(.*\)authorized_keys.*|SSHAuthorizedKeys \1'"${akf}"'|' "${NODE_CONFIG_FILE}" > "${NODE_CONFIG_FILE}.tmp"
  commandRestoreFile "${NODE_CONFIG_FILE}" "tmp"

  startNXServer

  return 0
}

setPermissionsNXHome ()
{
  commandChownChmodIfExist "$USER_NX:$ROOTGNAME" "600" "${NXHOME}/.ssh/authorized_keys"
  commandChownChmodIfExist "$USER_NX:$ROOTGNAME" "600" "${NXHOME}/.ssh/authorized_keys2"
}

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

  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
}

setShellUserMac ()
{
  checkNXUserExist

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

    runCommand "${DSCLCOMMAND} . -create /Users/${USER_NX} UserShell '${NXSHELL}'"\
                   "Cannot set shell for user: ${USER_NX} to '${NXSHELL}'" "error"

  else
    printMsg "User: ${USER_NX} doesn't exist" "error"
  fi
}

setShell ()
{
  isNetworkUser "${USER_NX}"

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

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

  elif [ "${system}" = "solaris" ];
  then
    setShellUserSolaris
  else
    setShellUserLinux
  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
}

setPersonalDBPerimissions ()
{
  commandChmod "1777" "${NX_VAR_DIR}/db"      "warn"
  commandChmod "1777" "${NX_VAR_DIR}/db/stat" "warn"
  commandChmod "1755" "${NX_VAR_DIR}/run"     "warn"
  commandChmod "1777" "${NX_VAR_DIR}/log"     "warn"
}

installPersonal ()
{
  initializeOperation "install"

  printOperationInfo "install"

  makeNXConfig
  makeNXConfigServerPersonal
  setAvailableSessionKey

  if [ -f "${LICENSE_FILE}.sample" ];
  then
    commandRmIfExist "${LICENSE_FILE}" "error"
    commandMv "${LICENSE_FILE}.sample" "${LICENSE_FILE}" "error"

    setPermForLicenseFile
  fi

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

  changeKeyAtConfigFile "${CONFIG_FILE}" 'SystemLogFile' "${NX_VAR_DIR}/log/server.log"

  updateConfigFile

  printSummaryInfo "install"

  exit 0
}

uninstallPersonal ()
{
  NX_PERSONAL=1
  initializeOperation "uninstall"
  printOperationInfo "uninstall"

  resetNXConfigServer
  removeETCDirectoryPersonal
  cleanPackageFiles

  printSummaryInfo "uninstall"
  exit 0
}

updatePersonal ()
{
  if [ "${system}" = "macosx" ];
  then
    if [ ! -f "${CONFIG_FILE}" ];
    then
      installPersonal
      return
    fi
  fi

  initializeOperation "update"
  printOperationInfo "update"

  makeConfBackup
  makeNXConfig

  if [ -f "${LICENSE_FILE}.sample" ];
  then
    commandRmIfExist "${LICENSE_FILE}" "error"
    commandMv "${LICENSE_FILE}.sample" "${LICENSE_FILE}" "error"

    setPermForLicenseFile
  fi

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

  printSummaryInfo "update"

  exit 0
}

runActionPackage ()
{
  if [ "${action}" = "--preuninstall" ] || [ "${action}" = "--pre-uninstall" ];
  then
    procedurePreuninstall
  fi

  if [ "${action}" = "--server-keygen" ] || [ "${action}" = "--keygen" ];
  then
    LOGFILE="${UPDATELOG}"
    createLogdirectory
    startLog

    isSSHSupported

    if [ "x${ret_isSSHSupported}" = "x0" ] && [ "x${NX_INSTALL_SILENT}" != "x1" ];
    then
      if [ "x${SSH_DISABLED_IN_LICENSE}" = "x1" ];
      then
        ${ECHOCOMMAND} "NX> 900 SSH connections are not supported on this server."
        return 0
      fi
    fi

    procedureServerKeygen
  fi

  if [ "${action}" = "--nxkeygen" ];
  then
    LOGFILE="${UPDATELOG}"
    createLogdirectory
    startLog

    isSSHSupported

    if [ "x${ret_isSSHSupported}" = "x0" ] && [ "x${NX_INSTALL_SILENT}" != "x1" ];
    then
      if [ "x${SSH_DISABLED_IN_CONFIG}" = "x1" ];
      then
        ${ECHOCOMMAND} "NX> 900 SSH connections are disabled on this server."
      else
        ${ECHOCOMMAND} "NX> 900 SSH connections are not supported on this server."
      fi

      return 0
    fi

    setupNXPath

    getNodeConfigFile

    FILE_AUTHORIZED_KEYS_ENABLED=0
    ONLYCHECKSSH="1"

    set_DSA_key=0
    set_RSA_key=0

    setAuthKey "${originalDSAKey}" "${currentDSAKey}"
    set_DSA_key=${ret_setAuthKey}

    setAuthKey "${originalRSAKey}" "${currentRSAKey}"
    set_RSA_key=${ret_setAuthKey}

    if [ ${set_DSA_key} -ne 0 ]
    then
      ${ECHOCOMMAND} "NX> 500 ERROR: Cannot set DSA keys."
    fi

    if [ ${set_RSA_key} -ne 0 ]
    then
      ${ECHOCOMMAND} "NX> 500 ERROR: Cannot set RSA keys."
    fi

    if [ ${set_DSA_key} -ne 0 ] && [ ${set_RSA_key} -ne 0 ];
    then
      return 0
    else

      setAuthorizedKeyFileName

      if [ "x${ret_setAuthorizedKeyFileName}" != "x0" ];
      then
        ${ECHOCOMMAND} "NX> 500 ERROR: Cannot determine authorized_key filename."

        return 0
      fi
    fi

    if [ "x${NX_INSTALL_SILENT}" != "x1" ];
    then
      ${ECHOCOMMAND} "NX> 900 SSH keys successfully generated."
    fi
  fi

  if [ "${action}" = "--keyrestore" ];
  then
    LOGFILE="${UPDATELOG}"
    createLogdirectory
    startLog

    procedureRestoreOriAuthKey "${currentRSAKey}" "${originalRSAKey}"
    procedureRestoreOriAuthKey "${currentDSAKey}" "${originalDSAKey}"

  fi

  if [ "${action}" = "--postupgrade" ];
  then
    procedurePostUpgrade "$2"
  fi

  if [ "${action}" = "--osquery" ];
  then
    runActionOsquery
  fi

  if [ "${action}" = "--startnxhtd" ];
  then
    runActionstartNXHtd
  fi

  if [ "${action}" = "--mode" ];
  then
    runActionChangeMode "${install_mode}"
  fi

  if [ "${action}" = "--enableservices" ];
  then
    runActionEnableInit "$service"
  fi

  if [ "${action}" = "--disableservices" ];
  then
    runActionDisableInit "$service"
  fi

  if [ "${action}" = "--checkservices" ];
  then
    runActionCheckInit
  fi

  if [ "$action" = "--install-pam" ];
  then
    runActionInstallPAM
  fi

  if [ "${action}" = "--checkpam" ];
  then
    runCheckPAM
  fi

  if [ "x${action}" = "x--pathsetup" ];
  then
    runPathSetup
  fi

  if [ "x$action" = "x--networksetup" ];
  then
    runNetworkSetup
  fi
}

runActionEnableInit ()
{
  nxservice="$1"

  LOGFILE="${INSTALLOG}"
  PROCESS="${INSTALL}"
  createLogdirectory
  startLog

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

    isSystemDSupported

    if [ ${ret_isSystemDSupported} = 1 ];
    then
      foundSystemdDirectory

      if [ -f "${SYSTEMD_DIRECTORY}/$SYSTEMD_SERVER_SERVICE" ];
      then
        runCommand "${SYSTEMCTLCOMMAND} enable $SYSTEMD_SERVER_SERVICE" "Cannot enable systemd service: $SYSTEMD_SERVER_SERVICE" "error"

        return 0
      fi
    else
      isUpstartSupported

      if [ ${ret_isUpstartSupported} = 1 ];
      then
        runUpstartServer
      fi
    fi

    addNXinit

  elif [ "${nxservice}" = "--nxd" ];
  then
    printMsg "Starting service: ${nxservice}" "cmd"
    addConnectionMethod "NX"
  elif [ "${nxservice}" = "--nxhtd" ];
  then
    isSupportedHtd
    if [ ${ret_isSupportedHtd} = 0 ];
    then
      printMsg "Cannot start service: ${nxservice}. Service is not supported" "cmd"
    else
      printMsg "Starting service: ${nxservice}" "cmd"
      addConnectionMethod "HTTP"
    fi

  elif [ "${nxservice}" = "--nxsshd" ];
  then
    isFreePackage
    if [ $ret_isFreePackage = 1 ];
    then
      printMsg "Cannot start service: ${nxservice}. Service is not supported" "cmd"
    else
      printMsg "Starting service: ${nxservice}" "cmd"
      addConnectionMethod "SSH"
    fi
  else
    printMsg "Unknown service: ${nxservice}" "cmd"
  fi
}

runActionDisableInit ()
{
  nxservice="$1"

  LOGFILE="${INSTALLOG}"
  PROCESS="${INSTALL}"
  createLogdirectory
  startLog

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

    isSystemDSupported

    if [ ${ret_isSystemDSupported} = 1 ];
    then
      foundSystemdDirectory

      if [ -f "${SYSTEMD_DIRECTORY}/$SYSTEMD_SERVER_SERVICE" ];
      then
        runCommand "${SYSTEMCTLCOMMAND} disable $SYSTEMD_SERVER_SERVICE" "Cannot disable systemd service: $SYSTEMD_SERVER_SERVICE" "error"

        return 0
      fi
    else
      isUpstartSupported

      if [ ${ret_isUpstartSupported} = 1 ];
      then
        disableUpstartServer
      fi
    fi

    removeNXinit

  elif [ "${nxservice}" = "--nxd" ];
  then
    printMsg "Stopping service: ${nxservice}" "cmd"
    removeConnectionMethod "NX"

  elif [ "${nxservice}" = "--nxhtd" ];
  then
    printMsg "Stopping service: ${nxservice}" "cmd"
    removeConnectionMethod "HTTP"
    removeHtdServerDaemonFileApple

  elif [ "${nxservice}" = "--nxsshd" ];
  then
    printMsg "Stopping service: ${nxservice}" "cmd"

    removeConnectionMethod "SSH"
  else
    printMsg "Unknown service: ${nxservice}" "cmd"
  fi

}

runActionCheckInit ()
{

  LOGFILE="${INSTALLOG}"
  PROCESS="${INSTALL}"
  createLogdirectory "nolog"
  startLog

  checkNXinit

  exit $ret_checkNXinit
}

runActionInstallPAM ()
{
  LOGFILE="${INSTALLOG}"
  PROCESS="${INSTALL}"
  createLogdirectory
  startLog

  installnxPAMScript
  installnxlimitsPAMScript
}

runActionChangeMode ()
{
  mode=$1

  server_cfg_file="${CONFIG_FILE}"

  if [ ! -f "${server_cfg_file}" ]  &&  [ -f "${server_cfg_file}.backup" ];
  then
    server_cfg_file="${server_cfg_file}.backup"
  fi

  current_mode=""

  getModefromConfigFile
  current_mode="${ret_getModefromConfigFile}"

  if [ "x${current_mode}" = "x" ];
  then
    if [ "x${mode}" = "xserver" ];
    then
      #
      # Now, nxserver is installed by default.
      #

      LOGFILE="${INSTALLOG}"
      PROCESS="${INSTALL}"
      createLogdirectory
      startLog

      setModeinConfigFile "server"

      return

    elif [ "x${mode}" = "xnode" ];
    then
      PACKAGE_NAME="node"

      NX_MPKG_PACKAGE="server" PACKAGE_TYPE="${PACKAGE_TYPE}" NX_CHANGE_MODE=1 "${NX_ROOT}/scripts/setup/nxrunner" --install "${SYSTEM}"
      NX_MPKG_PACKAGE="server" PACKAGE_TYPE="${PACKAGE_TYPE}" NX_CHANGE_MODE=1 "${NX_ROOT}/scripts/setup/nxplayer" --install "${SYSTEM}"
      NX_MPKG_PACKAGE="server" PACKAGE_TYPE="${PACKAGE_TYPE}" NX_CHANGE_MODE=1 "${NX_ROOT}/scripts/setup/nxnode" --install "${SYSTEM}"

      if [ ! -f "${server_cfg_file}" ];
      then
        commandCp "${NX_ROOT}/etc/server-$system.cfg.sample" "${server_cfg_file}" "error"
      fi

      LOGFILE="${INSTALLOG}"
      PROCESS="${INSTALL}"
      createLogdirectory
      startLog

      removeBasicEtcWebFiles
      setModeinConfigFile "node"

    elif [ "x${mode}" = "xplayer" ];
    then
      LOGFILE="${INSTALLOG}"
      PROCESS="${INSTALL}"
      createLogdirectory
      startLog

      shutdownServer

      removeNXinit

      setModeinConfigFile "player"

      return

    else
      printMsg "Unknown mode: $mode" "error"
    fi

  else

    printMsg "Switching between modes is not supported by this version" "error"

    return 0
  fi
}

runCheckPAM ()
{
  LOGFILE="${INSTALLOG}"
  PROCESS="${INSTALL}"
  createLogdirectory
  startLog

  parsePAMFile

  if [ "x${SUFFICIENT_PAM_WHEEL}" = "x1" ];
  then
    exit 1
  fi

  exit 0
}

runPathSetup ()
{
  if [ "x${OS}" = "xLinux" ];
  then
    commandInstall "root" "${ROOTGNAME}" "755" "${NX_ROOT}/scripts/init/nx.sh" \
                       "/etc/profile.d/nx.sh" "error"

    commandInstall "root" "${ROOTGNAME}" "755" "${NX_ROOT}/scripts/init/nx.csh" \
                       "/etc/profile.d/nx.csh" "error"

    ${SEDCOMMAND} -e 's:INSTALL_PATH:'"${NX_ROOT}"':' "/etc/profile.d/nx.sh" > \
                         "/etc/profile.d/nx.sh.tmp"

    commandRestoreFile "/etc/profile.d/nx.sh" "tmp"

    ${SEDCOMMAND} -e 's:INSTALL_PATH:'"${NX_ROOT}"':' "/etc/profile.d/nx.csh" > \
                         "/etc/profile.d/nx.csh.tmp"

    commandRestoreFile "/etc/profile.d/nx.csh" "tmp"

  else
    printMsgNoDot ""
    printMsg "Command is available only on Linux OS"
    printMsgNoDot ""
  fi
}

runNetworkSetup ()
{
  "$CDCOMMAND" /

  if [ "x$generation" = "xchild" ];
  then
    "$UMASKCOMMAND" 0
    "$NX_ROOT/scripts/setup/nxserver" --networksetup daemon </dev/null >/dev/null 2>/dev/null &
    exit 0
  fi

  if [ "x$generation" != "xdaemon" ];
  then
    "$SETSIDCOMMAND" "$NX_ROOT/scripts/setup/nxserver" --networksetup child  &
    exit 0
  fi

  exec >> "$INSTALLOG"
  exec 2>> "$INSTALLOG"
  exec 0</dev/null

  configureNxnetwork
  startNXServer
}

upgradeRemoteNodeFrom3 ()
{
  #
  # Using current multi-node server 3.x
  #  public key to get remote node available
  #  for multi-node server 4.x.
  #
  # Function should be executed during 'install'
  #  procedure, because when upgrading 3.x
  #  to 4.x nxserver executing 'install'
  #  procedure (remote node 3.5 does not
  #  have nxserver).
  #

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

    if [ -f "${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub" ];
    then
      runCommand "'${NXSHELL}' --keyadd \
                     ${NX_ROOT}/etc/keys/node.localhost.id_rsa.pub --protocol SSH" \
                         "Cannot upgrade remote node from 3.x"
    fi

    if [ -f "${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub" ];
    then
      runCommand "'${NXSHELL}' --keyadd \
                     ${NX_ROOT}/etc/keys/node.localhost.id_dsa.pub --protocol SSH" \
                         "Cannot upgrade remote node from 3.x"
    fi
  fi
}

upgradeMultinodeServerFrom3 ()
{

  #
  # Connecting to every remote node
  #  to made them available after
  #  upgrade from 3.x to 4.x
  #

  if [ "x${upgrade}" = "x1" ];
  then
    getLicenseInfo "${LICENSE_FILE}"
    base_lic_acronym="${ret_getLicenseAcronym}"

    if [ "x${base_lic_acronym}" = "xLASS" ];
    then
      runCommand "'${NXSHELL}' --nodedbupdate" "Cannot update remote nodes database"
    fi
  fi
}

removeOrphansServers ()
{

  #
  # Remove orphans server from database
  #

  getLicenseInfo "${LICENSE_FILE}"
  base_lic_acronym="${ret_getLicenseAcronym}"

  if [[ "${base_lic_acronym}" = *"CS"* ]];
  then
    runCommand "'${NXSHELL}' --serverdel 1 --orphans" "Cannot remove servers without parent from NX database." "warn"
  fi
}

runAction
