#!/bin/sh
############################################################################
#                                                                          #
#  Copyright (c) 2001, 2007 NoMachine, http://www.nomachine.com.           #
#                                                                          #
#  NXSERVER, NX protocol compression and NX extensions to this software    #
#  are copyright of NoMachine. Redistribution and use of the present       #
#  software is allowed according to terms specified in the file LICENSE    #
#  which comes in the source distribution.                                 #
#                                                                          #
#  Check http://www.nomachine.com/licensing.html for applicability.        #
#                                                                          #
#  NX and NoMachine are trademarks of NoMachine S.r.l.                     #
#                                                                          #
#  All rigths reserved.                                                    #
#                                                                          #
############################################################################
VERSION="3.2.0-7"
PRODUCT_NAME="NX Server $VERSION"
CONFIG_VERSION="1.0"

setupNXPath() {
  if [ "x$1" != "x" ]
  then
    NODE_ROOT="$1/NX"
  else
    NODE_ROOT="/usr/NX"
  fi

  NXSHELL="$NODE_ROOT/bin/nxserver"
  CONFIG_FILE="$NODE_ROOT/etc/server.cfg"
  LICENSE_FILE="$NODE_ROOT/etc/server.lic"
  NODE_LICENSE_FILE="$NODE_ROOT/etc/node.lic"

  WRAPPER="$NODE_ROOT/bin/nxuexec"


  NXWTMPADDSH="$NODE_ROOT/scripts/restricted/nxwtmpadd.sh"
  NXWTMPDELSH="$NODE_ROOT/scripts/restricted/nxwtmpdel.sh"
  NXCOOKIEGENSH="$NODE_ROOT/scripts/restricted/nxcookiegen.sh"
  NXPASSWDSH="$NODE_ROOT/scripts/restricted/nxpasswd.sh"
  NXQUOTAADD="$NODE_ROOT/scripts/restricted/nxquotaadd.sh"
  NXCONFIGURATIONSH="$NODE_ROOT/scripts/restricted/nxconfigure.sh"
  NXGROUPADDSH="$NODE_ROOT/scripts/restricted/nxgroupadd.sh"
  NXSTATISTICSDB="$NODE_ROOT/var/db/stat/statistics.db"
  NXSTATISTICS="$NODE_ROOT/var/db/stat"

  INSTALLOG="$NODE_ROOT/var/log/install"
  UPDATELOG="$NODE_ROOT/var/log/update"
  UNINSTALLOG="$NODE_ROOT/var/log/uninstall"
  LOGFILE=""
}

setupNXPath ""

SSHDPort="22"

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

PREFIX="NX>"

NX_SETUP_VERSION="nxsetup 1.2.2"

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

PACKAGE="node"

currentTime=`date +'%a %b %d %T %Y'`

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$system" = "x" -a -f /etc/release ];
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 /bin/sleep ];
then
  SLEEPCOMMAND="/bin/sleep"
else
  SLEEPCOMMAND="sleep"
fi


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

printMsgNoDot () {
TXT=$1
  if [ "$TXT" = "" ];
  then
    return 0;
  fi

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

  case "$2" in
    "warn"  ) process="$WARNING";TXT="WARNING: $TXT";logtype="show";SHOWWARNINFO="yes";;
    "error" ) process="$ERROR";TXT="ERROR: $TXT";logtype="show";;
    "cmd"   ) process="$PROCESS";logtype="log";;
    "nolog" ) process="$PROCESS";logtype="nolog";;
    ""      ) process="$PROCESS";logtype="show";;
    *       ) process="$PROCESS";;
  esac

  if [ "$LOGFILE" = "" ];
  then
    logtype="nolog";
  fi

  case "$logtype" in
   "nolog"   ) echo "$PREFIX $PROCESS $TXT";;
   "log"     ) echo "$PREFIX $PROCESS $TXT" >> $LOGFILE;;
   "show"    ) echo "$PREFIX $PROCESS $TXT";echo "$PREFIX $PROCESS $TXT" >> $LOGFILE;;
   ""        ) echo "$PREFIX $PROCESS $TXT";;
   *         ) echo "$PREFIX $PROCESS $TXT";;
 esac

}

printMsg () {
  #txt of the message
  TXT=$1
  if [ "$TXT" = "" ];
  then
    return 0;
  fi

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

  case "$2" in
    "warn"  ) process="$WARNING";TXT="WARNING: $TXT";logtype="show";SHOWWARNINFO="yes";;
    "error" ) process="$ERROR";TXT="ERROR: $TXT";logtype="show";;
    "cmd"   ) process="$PROCESS";logtype="log";;
    "nolog" ) process="$PROCESS";logtype="nolog";;
    ""      ) process="$PROCESS";logtype="show";;
    *       ) process="$PROCESS";;    
  esac

  if [ "$LOGFILE" = "" ];
  then
    logtype="nolog";
  fi

  case "$logtype" in
    "nolog"   ) echo "$PREFIX $PROCESS $TXT.";;
    "log"     ) echo "$PREFIX $PROCESS $TXT." >> $LOGFILE;;
    "show"    ) echo "$PREFIX $PROCESS $TXT.";echo "$PREFIX $PROCESS $TXT." >> $LOGFILE;;
    ""        ) echo "$PREFIX $PROCESS $TXT.";;
    *         ) echo "$PREFIX $PROCESS $TXT.";;
  esac

}

LastCommand=""

runShCommand () {
  if [ "$1" = "" ];
  then
    return 1
  else
    command="$1"
  fi

  outCommand=`/bin/bash -c "$command" 2>&1`

  if [ $? != 0 ];
  then
      LastCommand="Error is: $outCommand"
  fi
}

runCommand () {

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

  if [ "$2" = "" ];
  then
    return 1
  else
    message="$2"
  fi
  
  if [ "$3" = "" ];
  then
    important="NO"
  else
    important="YES"
  fi

  printMsg "Running: $command" "cmd"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    if [ "$important" = "YES" ];
    then
      if [ "x$outCommand" != "x" ];
      then 
        printMsg "Output: $outCommand" "error"
      fi
      printMsg "$message" "error"
      exit 1
    else
      if [ "x$outCommand" != "x" ];
      then 
        printMsg "Output: $outCommand" "cmd"
      fi
      printMsg "$message" "warn"
    fi
  else
    if [ "x$outCommand" != "x" ];
    then 
      printMsg "Output: $outCommand" "cmd"
    fi
    printMsg "Result: OK" "cmd"
  fi

}

removeNXNodesDB () {
  if [ -f "$NODE_ROOT/etc/nodes.db" ];
  then
    runCommand "$RMCOMMAND -f '$NODE_ROOT/etc/nodes.db'" "Cannot remove $NODE_ROOT/etc/nodes.db file" "warn"
  fi
}

stopNXServer () {
  if [ -f "$FILE_AUTHORIZED_KEYS" ];
  then
    runCommand "$RMCOMMAND -f '$FILE_AUTHORIZED_KEYS'" "Cannot remove $FILE_AUTHORIZED_KEYS file" "warn"
  fi
}


startNXServer () {
  if [ -f "$FILE_AUTHORIZED_KEYS" ];
  then
    runCommand "$RMCOMMAND -f '$FILE_AUTHORIZED_KEYS'" "Cannot remove $FILE_AUTHORIZED_KEYS file" "warn"
  fi
  runCommand "$CPCOMMAND -p '$NODE_ROOT/home/nx/.ssh/default.id_dsa.pub' '$FILE_AUTHORIZED_KEYS'" "Cannot start NX Server" "warn"
}

stopNXStat () {

  stopStatistics=`$NXSHELL --statistics stop < /dev/null 2>&1`
  result_stop=$?
  result_stop=`echo "$stopStatistics" `
   
  result_stop_msg=`echo "$result_stop" | grep "NX> 7"`
  echo "$result_stop_msg"
  
  if [ -f "$NXSHELL" ];
  then
    runCommand "$NXSHELL --statistics stop" "Cannot stop NX statistics" 
  fi
}

startNXStat () {
  startStatistics=`$NXSHELL --statistics start < /dev/null 2>&1`
  result=`echo "$startStatistics" `
  
  result_msg=`echo "$result" | grep "NX> 7"`
  outPUTLog=`echo ${result_msg} | sed -e 's/NX> 723//g'`
  outPUTLog=`echo ${outPUTLog}| sed -e 's/NX> 709/NX> 701/g' `
  printMsgNoDot "${outPUTLog}" "cmd"
  if [ "x$result_msg" != "x" ];
  then
    echo "$result_msg"
  fi
  
  if [ $? != 0 ];
    then
     outPUTLog=`echo "Cannot start NX statistics:" && echo "$startStatistics"`
     printMsg "$outPUTLog" "cmd"
     outPUTConsole=`echo "Cannot start NX statistics: NX statistics are disabled for this server"`
     printMsg "$outPUTConsole" "nolog"
  fi
}

updateAutorizedKey () {
  if [ -f "$FILE_AUTHORIZED_KEYS" ];
  then
    runCommand "$RMCOMMAND -f '$FILE_AUTHORIZED_KEYS'" "Cannot remove '$FILE_AUTHORIZED_KEYS' file" "warn"
    runCommand "$CPCOMMAND -p '$NODE_ROOT/home/nx/.ssh/default.id_dsa.pub' '$FILE_AUTHORIZED_KEYS'" "Cannot start NX Server" "warn"
    selinuxOperations
  fi
}

createLogdirectory () {
  if [ ! -d "$NODE_ROOT/var/log" ];
  then
    command="mkdir -p '$NODE_ROOT/var/log'"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ $? != 0 ];
    then
      LOGFILE=""
      printMsg "Cannot create log directory: $NODE_ROOT/var/log" "warn"
      printMsg "All informations are being redirect to stdout"
    fi
  fi
}

startLog () {

  if [ -f $LOGFILE ];
  then
    command="echo ' ' >> $LOGFILE"
  else 
    command="echo ' ' > $LOGFILE"
  fi
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ "$?" != 0 ];
  then
    tmp="$LOGFILE"
    LOGFILE=""
    printMsg "Cannot create logfile: $tmp:" "warn"
    printMsg "'$outCommand'" "warn"
    printMsg "All informations are being redirect to stdout" "warn"
  fi
  if [ "$LOGFILE" != "" ];
  then
    command="echo '' | tee -a $LOGFILE 2>&1"
    outCommand=`/bin/bash -c "$command" 2>&1` 
    if [ "$?" != 0 ];
    then
      tmp="$INSTALLOG"
      LOGFILE=""
      printMsg "Cannot initialize logfile: $tmp:" "warn"
      printMsg "Command: '$command'" "warn"
      printMsg "'$outCommand'" "warn"
      printMsg "All informations are being redirect to stdout" "warn"
    fi
  fi
}

resetPermissionsServer () {
  if [ -f "$NXCOOKIEGENSH" ];
  then
    runCommand "chmod 755 $NXCOOKIEGENSH" "Cannot fix permissions of '$NXCOOKIEGENSH' script"
    runCommand "chown root:root $NXCOOKIEGENSH" "Cannot fix ownership of '$NXCOOKIEGENSH' script"
  fi
  if [ -f "$NXWTMPADDSH" ];
  then
    runCommand "chmod 755 $NXWTMPADDSH" "Cannot fix permissions of '$NXWTMPADDSH' script"
    runCommand "chown root:root $NXWTMPADDSH" "Cannot fix ownership of '$NXWTMPADDSH' script"
  fi
  if [ -f "$NXWTMPDELSH" ];
  then
    runCommand "chmod 755 $NXWTMPDELSH" "Cannot fix permissions of '$NXWTMPDELSH' script"
    runCommand "chown root:root $NXWTMPDELSH" "Cannot fix ownership of '$NXWTMPDELSH' script"
  fi
  if [ -f "$NXPASSWDSH" ];
  then
    runCommand "chmod 744 $NXPASSWDSH" "Cannot fix permissions of '$NXPASSWDSH' script"
    runCommand "chown root:root $NXPASSWDSH" "Cannot fix ownership of '$NXPASSWDSH' script"
  fi
  if [ -f "$NXQUOTAADD" ];
  then
    runCommand "chmod 744 $NXQUOTAADD" "Cannot fix permissions of '$NXQUOTAADD' script"
    runCommand "chown root:root $NXQUOTAADD" "Cannot fix ownership of '$NXQUOTAADD' script"
  fi
  if [ -f "$NXCONFIGURATIONSH" ];
  then
    runCommand "chmod 744 $NXCONFIGURATIONSH" "Cannot fix permissions of '$NXCONFIGURATIONSH' script"
    runCommand "chown root:root $NXCONFIGURATIONSH" "Cannot fix ownership of '$NXCONFIGURATIONSH' script"
  fi
  if [ -f "$NXGROUPADDSH" ];
  then
    runCommand "chmod 744 $NXGROUPADDSH" "Cannot fix permissions of '$NXGROUPADDSH' script"
    runCommand "chown root:root $NXGROUPADDSH" "Cannot fix ownership of '$NXGROUPADDSH' script"
  fi
}

checkSessregPath () {
  if [ ! -r $CONFIG_FILE ];
  then
    return 1
  fi
  command="grep CommandSessreg $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    if [ "$system" = "solaris" ];
    then
      echo "#
# Sets path and name of the command 'sessreg'.
#
#CommandSessreg = \"/usr/X/bin/sessreg\"
">> $CONFIG_FILE
    else
      echo "#
# Sets path and name of the command 'sessreg'.
#
#CommandSessreg = \"/usr/X11R6/bin/sessreg\"
">> $CONFIG_FILE
    fi
  fi
}

setNxsessregPermisions () {

  if [ -f "$NXWTMPADDSH" ];
    then
      runCommand "chown root:root '$NXWTMPADDSH'" "Cannot change ownership of '$NXWTMPADDSH' to 'root:root'" "error"
      runCommand "chmod 744 '$NXWTMPADDSH'" "Cannot set permissions attributes for '$NXWTMPADDSH' to '744'" "error"
      runCommand "chmod u+s '$NXWTMPADDSH'" "Cannot set permissions attributes for '$NXWTMPADDSH' to 'u+s'" "error"
    else 
      printMsg "No such file: $NXWTMPADDSH" "error"
      exit 1
  fi

  if [ -f "$NXCOOKIEGENSH" ];
    then
      runCommand "chown root:root '$NXCOOKIEGENSH'" "Cannot change ownership of '$NXCOOKIEGENSH' to 'root:root'" "error"
      runCommand "chmod 744 '$NXCOOKIEGENSH'" "Cannot set permissions attributes for '$NXCOOKIEGENSH' to '744'" "error"
      runCommand "chmod u+s '$NXCOOKIEGENSH'" "Cannot set permissions attributes for '$NXCOOKIEGENSH' to 'u+s'" "error"
    else
      printMsg "No such file: $NXCOOKIEGENSH" "error"
      exit 1
  fi

  if [ -f "$NXWTMPDELSH" ];
    then
      runCommand "chown root:root '$NXWTMPDELSH'" "Cannot change ownership of '$NXWTMPDELSH' to 'root:root'" "error"
      runCommand "chmod 744 '$NXWTMPDELSH'" "Cannot set permissions attributes for '$NXWTMPDELSH' to '744'" "error"
      runCommand "chmod u+s '$NXWTMPDELSH'" "Cannot set permissions attributes for '$NXWTMPDELSH' to 'u+s'" "error"
    else 
      printMsg "No such file: $NXWTMPDELSH" "error"
      exit 1
  fi

}

setNxUserMngshPermissions () {
  if [ -f "$NXPASSWDSH" ]
    then
      runCommand "chown root:root '$NXPASSWDSH'" "Cannot change ownership of '$NXPASSWDSH' to 'root:root'"
      runCommand "chmod 744 '$NXPASSWDSH'" "Cannot set permissions attributes for '$NXPASSWDSH' to '744'"
      runCommand "chmod u+s '$NXPASSWDSH'" "Cannot set permissions attributes for '$NXPASSWDSH' to 'u+s'" 
    else
      printMsg "No such file: $NXPASSWDSH" "warn"
  fi

  if [ -f "$NXCONFIGURATIONSH" ]
    then
      runCommand "chown root:root '$NXCONFIGURATIONSH'" "Cannot change ownership of '$NXCONFIGURATIONSH' to 'root:root'"
      runCommand "chmod 744 '$NXCONFIGURATIONSH'" "Cannot set permissions attributes for '$NXCONFIGURATIONSH' to '744'"
      runCommand "chmod u+s '$NXCONFIGURATIONSH'" "Cannot set permissions attributes for '$NXCONFIGURATIONSH' to 'u+s'" 
    else
      printMsg "No such file: $NXCONFIGURATIONSH" "warn"
  fi

  if [ -f "$NXGROUPADDSH" ]
    then
      runCommand "chown root:root '$NXGROUPADDSH'" "Cannot change ownership of '$NXGROUPADDSH' to 'root:root'"
      runCommand "chmod 744 '$NXGROUPADDSH'" "Cannot set permissions attributes for '$NXGROUPADDSH' to '744'"
      runCommand "chmod u+s '$NXGROUPADDSH'" "Cannot set permissions attributes for '$NXGROUPADDSH' to 'u+s'" 
    else
      printMsg "No such file: $NXGROUPADDSH" "warn"
  fi

  if [ -f "$NXQUOTAADD" ]
    then
      runCommand "chown root:root '$NXQUOTAADD'" "Cannot change ownership of '$NXQUOTAADD' to 'root:root'"
      runCommand "chmod 744 '$NXQUOTAADD'" "Cannot set permissions attributes for '$NXQUOTAADD' to '744'"
      runCommand "chmod u+s '$NXQUOTAADD'" "Cannot set permissions attributes for '$NXQUOTAADD' to 'u+s'" 
    else
      printMsg "No such file: $NXQUOTAADD" "warn"
  fi
}

setNxStatisticDBPermissions () {
  if [ ! -d "$NXSTATISTICS" ];
  then
    printMsg "Directory '$NXSTATISTICS' does not exists" "warn"
  else
    if [ ` ls -dl "$NXSTATISTICS" | $AWKCOMMAND '{print $3}' ` != "nx" ];
    then
      #printMsg "$NXSTATISTICS directory has wrong ownership. Correct ownership is nx" "warn"
      runCommand "chown -R nx '$NXSTATISTICS'" "Cannot set ownership for: '$NXSTATISTICS' to: 'nx'"
    fi

    if [ ` ls -dl "$NXSTATISTICS" | $AWKCOMMAND '{print $1}' ` != "drwxrwx---" ];
    then
       #printMsg "$NXSTATISTICS directory has wrong permissions Correct permissions are 0770" "warn"
      runCommand "chmod  0770 '$NXSTATISTICS'" "Cannot set permissions for: '$NXSTATISTICS' to: '0770'"
    fi

    if [ -f "$NXSTATISTICSDB" ];
    then 
      if [ ` ls -l "$NXSTATISTICSDB" | $AWKCOMMAND '{print $3}'` != "nx"  ];
      then
        printMsg "Statistics DB file : $NXSTATISTICSDB has wrong ownership. Correct ownership is nx" "warn"
        runCommand "chown -R nx '$NXSTATISTICSDB'" "Cannot set ownership for: '$NXSTATISTICSDB' to: 'nx'"
      fi
    fi

    if [ -f "$NXSTATISTICSDB" ];
    then
      if [ ` ls -l "$NXSTATISTICSDB" | $AWKCOMMAND '{print $1}'` != "-rw-r-----"  ];
      then
        printMsg "Statistics DB file : $NXSTATISTICSDB has wrong permissions. Correct permissions are 0640." "warn"
        runCommand "chmod  0640 '$NXSTATISTICSDB'" "Cannot set permissions for: '$NXSTATISTICSDB' to: '0640'"
      fi
    fi
  fi

}

removeSystemConfig () {

  rcFile="/etc/rc.local"

  if [ -f "$rcFile" ];
  then
    if grep "#nxsetup .*:" "$rcFile" > /dev/null
    then
      if sed -e "/^#nxsetup .*:/,/^#nxsetup end\./d" < "$rcFile" > "$rcFile.tmp"
      then
        runCommand "$CPCOMMAND -f '$rcFile.tmp' '$rcFile'" "Unable to copy '$rcFile.tmp' to '$rcFile'" "warn"
        runCommand "$RMCOMMAND -f '$rcFile.tmp'" "Unable to remove '$rcFile.tmp'" "warn"
      fi
    fi
  fi
}

removeNXinit () {

  runCommand "$RMCOMMAND -f /etc/init.d/nxserver" "Unable to remove '/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" = "debian" ];
    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

  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/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/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/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

  fi
}


addNXinit () {

 runCommand "cat $NODE_ROOT/scripts/init/nxserver > /etc/init.d/nxserver" "Unable to create: '/etc/init.d/nxserver'" "warn"
 runCommand "chmod +x /etc/init.d/nxserver" "Cannot set permissions of '/etc/init.d/nxserver' file" "warn"

 temppdir=`pwd`

 if [ "$system" = "solaris" ];
  then
      if [ -d /etc/rc0.d ];
      then
        cd /etc/rc0.d
        if [ ! -h /etc/rc0.d/K01nxserver ];
        then
          runCommand "ln -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 "ln -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 "ln -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 "ln -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 "ln -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 "ln -sf ../nxserver S99nxserver" "Unable to create link: '/etc/init.d/rc3.d/S99nxserver'" "warn"
       cd /etc/init.d/rc2.d
       runCommand "ln -sf ../nxserver S99nxserver" "Unable to create link: '/etc/init.d/rc2.d/S99nxserver'" "warn"
       cd /etc/init.d/rc5.d
       runCommand "ln -sf ../nxserver S99nxserver" "Unable to create link: '/etc/init.d/rc5.d/S99nxserver'" "warn"
       cd /etc/init.d/rc6.d
       runCommand "ln -sf ../nxserver K01nxserver" "Unable to create link: '/etc/init.d/rc6.d/K01nxserver'" "warn"
       cd /etc/init.d/rc0.d
       runCommand "ln -sf ../nxserver K01nxserver" "Unable to create link: '/etc/init.d/rc0.d/K01nxserver'" "warn"
    elif [ "$system" = "debian" ];
      then
        cd /etc/rc3.d
       runCommand "ln -sf ../init.d/nxserver S99nxserver" "Unable to create link: '/etc/rc3.d/S99nxserver'" "warn"
       cd /etc/rc2.d
       runCommand "ln -sf ../init.d/nxserver S99nxserver" "Unable to create link: '/etc/rc2.d/S99nxserver'" "warn"
       cd /etc/rc5.d
       runCommand "ln -sf ../init.d/nxserver S99nxserver" "Unable to create link: '/etc/rc5.d/S99nxserver'" "warn"
       cd /etc/rc6.d
       runCommand "ln -sf ../init.d/nxserver K01nxserver" "Unable to create link: '/etc/rc6.d/K01nxserver'" "warn"
       cd /etc/rc0.d
       runCommand "ln -sf ../init.d/nxserver K01nxserver" "Unable to create link: '/etc/rc0.d/K01nxserver'" "warn"
    else
        cd /etc/rc.d/rc3.d
        runCommand "ln -sf /etc/init.d/nxserver S99nxserver" "Unable to create link: '/etc/rc.d/rc3.d/S99nxserver'" "warn"
        cd /etc/rc.d/rc2.d
        runCommand "ln -sf /etc/init.d/nxserver S99nxserver" "Unable to create link: '/etc/rc.d/rc2.d/S99nxserver'" "warn"
        cd ../rc5.d
        runCommand "ln -sf /etc/init.d/nxserver S99nxserver" "Unable to create link: '/etc/rc.d/rc5.d/S99nxserver'" "warn"
        cd ../rc6.d
        runCommand "ln -sf /etc/init.d/nxserver K01nxserver" "Unable to create link: '/etc/rc.d/rc6.d/K01nxserver'" "warn"
        cd ../rc0.d
        runCommand "ln -sf /etc/init.d/nxserver K01nxserver" "Unable to create link: '/etc/rc.d/rc0.d/K01nxserver'" "warn"
     fi
  cd $temppdir

}

removeNXSystemSetup () {
  if [ -f "$rcBash" ];
  then
    if grep "#$NX_SETUP_VERSION" "$rcBash" 1>/dev/null
    then
      if sed -e "/^#nxsetup .*:/,/^#nxsetup end\./d" < "$rcBash" > "$rcBash.tmp"
      then
        runCommand "$CPCOMMAND -f '$rcBash.tmp' '$rcBash'" "Unable to copy '$rcBash.tmp' to '$rcBash'" "warn"
        runCommand "$RMCOMMAND -f '$rcBash.tmp'" "Unable to remove '$rcBash.tmp'" "warn"
      fi
    fi
  fi

  if [ -f "$rcCsh" ];
  then
    if grep "#$NX_SETUP_VERSION" "$rcCsh" 1>/dev/null
    then
      if sed -e "/^#nxsetup .*:/,/^#nxsetup end\./d" < "$rcCsh" > "$rcCsh.tmp"
      then
        runCommand "$CPCOMMAND -f '$rcCsh.tmp' '$rcCsh'" "Unable to copy '$rcCsh.tmp' to '$rcCsh'" "warn"
        runCommand "$RMCOMMAND -f '$rcCsh.tmp'" "Unable to remove '$rcCsh.tmp'" "warn"
      fi
    fi
  fi
}

addNXUserLinux () {
  if [ "x$system" != "xdebian" ]
  then
    sysuser=`useradd --help 2>&1|grep "\-r"`;
    if [ "x$sysuser" != "x" ]
    then
      sysuser="-r"
    else
      sysuser=""
    fi

    if [ "x$system" = "xmandrake" -o "x$system" = "xfedora" ];
    then
      runCommand "useradd -p '*' -d '$NODE_ROOT/home/nx' $sysuser -M nx" "Cannot add user: nx to the system" "error"
    else
      runCommand "useradd -p '*' -d '$NODE_ROOT/home/nx' $sysuser nx" "Cannot add user: nx to the system" "error"
    fi
  else
    runCommand "adduser --system --disabled-password --home $NODE_ROOT/home/nx nx" "Cannot add user: nx to the system" "error"
    runCommand "usermod -p '*' nx " "Cannot unlock user: nx" "error"
  fi

  if [ -f /etc/nscd.conf ] 
  then
    $NSCDCOMMAND --invalidate passwd 
  else
    result=`id nx 2>&1`
    if [ $? = 0 ];
    then
      $SLEEPCOMMAND 2
    fi
  fi
}

setShell () {
  if [ "x$system" = "xsolaris" ];
  then
   setShellUserSolaris
  else
    setShellUserLinux
  fi
}

setShellUserLinux () {
  command="echo '$NXSHELL' | /usr/bin/chsh nx"
  printMsg "Command: $command" "cmd"
  outCommand=`/bin/bash -c "$command" 2>&1` 
  if [ "$?" != 0 ];
  then
    printMsg "$outCommand" "cmd"
    printMsg "Cannot set shell for user: nx to '$NXSHELL'" "error"
    runCommand "userdel nx" "Cannot delete user: nx from the system" "error"
    exit 1
  else
    printMsg "$outCommand" "cmd"
    printMsg "Result: OK" "cmd"
  fi
}

addNXUserSolaris () {
  runCommand "useradd -d '$NODE_ROOT/home/nx' nx" "Cannot add user: nx to the system" "error"
}

enableNxUser () {

  command="$NODE_ROOT/bin/nxnode --enablenxuser"
  printMsg "Command: $command" "cmd"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "cmd"
      printMsg "Cannot unlock account for user: nx" "error"
      runCommand "userdel nx" "Cannot delete user: nx from the system" "error"
      exit 1
  else
    printMsg "$outCommand" "cmd"
    printMsg "Result: OK" "cmd"
  fi
}

setShellUserSolaris () {

  command="passwd -d nx"
  printMsg "Command: $command" "cmd"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "cmd"
      printMsg "Cannot unlock account for user: nx" "error"
      runCommand "userdel nx" "Cannot delete user: nx from the system" "error"
      exit 1
  else
    printMsg "$outCommand" "cmd"
    printMsg "Result: OK" "cmd"
  fi

  enableNxUser

  command="usermod -s '$NXSHELL' nx"
  printMsg "Command: $command" "cmd"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ "$?" != 0 ];
  then
    printMsg "$outCommand" "cmd"
    printMsg "Cannot set shell for user: nx to '$NXSHELL'" "error"
    runCommand "userdel nx" "Cannot delete user: nx from the system" "error"
    exit 1
  else
    printMsg "$outCommand" "cmd"
    printMsg "Result: OK" "cmd"
  fi
}

removeNXUser () {

  runCommand "id nx" "Cannot delete user: nx from the system" "error"

  printMsg "Deleting user: nx from the system"

  runCommand "userdel nx" "Cannot delete user: nx from the system" "error"
}

genNXUsersKeys () {

  if [ ! -d "$NODE_ROOT/etc/keys" ];
  then
    mkdir "$NODE_ROOT/etc/keys"
  fi
  
  if [ -f "$NODE_ROOT/etc/users.id_dsa" ];
  then
    printMsg "Found file: $NODE_ROOT/etc/users.id_dsa" "warn"
    printMsg "Skipping generation keys for NX users authentication" "warn"
    $MVCOMMAND "$NODE_ROOT/etc/users.id_dsa" "$NODE_ROOT/etc/keys/node.localhost.id_dsa"
    $MVCOMMAND "$NODE_ROOT/etc/users.id_dsa.pub" "$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub"
    return
  fi

  if [ -f "$NODE_ROOT/etc/keys/node.localhost.id_dsa" ];
  then
    printMsg "Found file: $NODE_ROOT/etc/keys/node.localhost.id_dsa" "warn"
    printMsg "Skipping generation keys for NX users authentication" "warn"
    return
  fi

  runCommand "ssh-keygen -q -t dsa -N '' -f '$NODE_ROOT/etc/keys/node.localhost.id_dsa'" "Skipping generation of SSH keys for NX users authentication" "error"
}

archiveNXUsersKeys () {

  if [ "$system" != "solaris" ];
  then
    if [ -f "$NODE_ROOT/etc/users.id_dsa" ];
    then
      printMsg "Saving private key to: $NODE_ROOT/etc/keys/node.localhost.id_dsa.backup" "warn"
      printMsg "Saving public key to: $NODE_ROOT/etc/keys/node.localhost.id_dsa.pub.backup" "warn"
    fi

    if [ -f "$NODE_ROOT/etc/keys/node.locahost.id_dsa" ];
    then
      printMsg "Saving private key to: $NODE_ROOT/etc/keys/node.localhost.id_dsa.backup" 
      printMsg "Saving public key to: $NODE_ROOT/etc/keys/node.localhost.id_dsa.pub.backup" 
    fi
 
    if [ -f "$NODE_ROOT/etc/users.id_dsa" ];
    then
      runCommand "$MVCOMMAND '$NODE_ROOT/etc/users.id_dsa' '$NODE_ROOT/etc/keys/node.localhost.id_dsa.backup'" "Cannot move private key '$NODE_ROOT/etc/users.id_dsa' to '$NODE_ROOT/etc/keys/node.localhost.id_dsa.backup'" "error"
      runCommand " $MVCOMMAND '$NODE_ROOT/etc/users.id_dsa.pub' '$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub.backup'" "Cannot move public key '$NODE_ROOT/etc/users.id_dsa.pub' to '$NODE_ROOT/etc/keys/node.localhost.id_dsa.backup'" "error"
    fi

    if [ -f "$NODE_ROOT/etc/keys/node.locahost.id_dsa" ];
    then
      runCommand "$MVCOMMAND '$NODE_ROOT/etc/keys/node.localhost.id_dsa' '$NODE_ROOT/etc/keys/node.localhost.id_dsa.backup'" "Cannot move private key '$NODE_ROOT/etc/keys/node.localhost.id_dsa' to '$NODE_ROOT/etc/keys/node.localhost.id_dsa.backup'" "error"
      runCommand " $MVCOMMAND '$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub' '$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub.backup'" "Cannot move public key '$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub' to '$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub.backup'" "error"
    fi
  fi

}

makeNXConfigServer () {

  if [ -f "$NODE_ROOT/etc/passwords.db" ];
  then
    printMsgNoDot "Found file: $NODE_ROOT/etc/passwords.db. In order to not overwrite it," "warn"
    printMsgNoDot "the sample configuration file: $NODE_ROOT/etc/passwords.db.sample shipped" "warn"
    printMsg "with this version of NX Server will not be copied to: $NODE_ROOT/etc/passwords.db" "warn"
    printMsg "Please check your NX Server passwords.db file when the installation completes" "warn"
  else
    runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/passwords.db.sample' '$NODE_ROOT/etc/passwords.db'" "Cannot copy '$NODE_ROOT/etc/passwords.db.sample' to '$NODE_ROOT/etc/passwords.db'." "error"
  fi

  if [ ! -f "$NODE_ROOT/etc/passwords.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/passwords.db.lock'" "Cannot create '$NODE_ROOT/etc/passwords.db.lock' file" "error"
     runCommand "chown nx:root '$NODE_ROOT/etc/passwords.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/passwords.db.lock' to 'nx:root'" "error"
  fi

  if [ -f "$NODE_ROOT/etc/administrators.db" ];
  then
    printMsgNoDot "Found file: $NODE_ROOT/etc/administrators.db. In order to not overwrite it," "warn"
    printMsgNoDot "the sample configuration file: $NODE_ROOT/etc/administrators.db.sample shipped" "warn"
    printMsg "with this version of NX Server will not be copied to: $NODE_ROOT/etc/administrators.db" "warn"
    printMsg "Please check your NX Server administrators.db file when the installation completes" "warn"
  else
    runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/administrators.db.sample' '$NODE_ROOT/etc/administrators.db'" "Cannot copy '$NODE_ROOT/etc/adminisrators.db.sample' to '$NODE_ROOT/etc/administrators.db'." "error"
  fi

  if [ ! -f "$NODE_ROOT/etc/administrators.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/administrators.db.lock'" "Cannot create '$NODE_ROOT/etc/administrators.db.lock' file" "error"
     runCommand "chown nx:root '$NODE_ROOT/etc/administrators.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/administrators.db.lock' to '0600'" "error"
  fi

 if [ -f "$NODE_ROOT/etc/guests.db" ];
  then
    printMsgNoDot "Found file $NODE_ROOT/etc/guests.db. In order to not overwrite it," "warn"
    printMsgNoDot "the sample configuration file $NODE_ROOT/etc/guests.db.sample shipped" "warn"
    printMsg "with this version of NX Server will not be copied to $NODE_ROOT/etc/guests.db" "warn"
    printMsg "Please check your NX Server guests.db file when the installation completes" "warn"
  else
    runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/guests.db.sample' '$NODE_ROOT/etc/guests.db'" "Cannot copy '$NODE_ROOT/etc/guests.db.sample' to '$NODE_ROOT/etc/guests.db'." "error"
  fi

  if [ ! -f "$NODE_ROOT/etc/guests.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/guests.db.lock'" "Cannot create '$NODE_ROOT/etc/guests.db.lock' file" "error"
     runCommand "chown nx:root '$NODE_ROOT/etc/guests.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/guests.db.lock' to 'nx:root'" "error"
  fi

 if [ -f "$NODE_ROOT/etc/profiles.db" ];
  then
    printMsgNoDot "Found file $NODE_ROOT/etc/profiles.db. In order to not overwrite it," "warn"
    printMsgNoDot "the sample configuration file $NODE_ROOT/etc/profiles.db.sample shipped" "warn"
    printMsg "with this version of NX Server will not be copied to $NODE_ROOT/etc/profiles.db" "warn"
    printMsg "Please check your NX Server profiles.db file when the installation completes" "warn"
  else
    runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/profiles.db.sample' '$NODE_ROOT/etc/profiles.db'" "Cannot copy '$NODE_ROOT/etc/profiles.db.sample' to '$NODE_ROOT/etc/profiles.db'." "error"
  fi

  if [ ! -f "$NODE_ROOT/etc/profiles.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/profiles.db.lock'" "Cannot create '$NODE_ROOT/etc/profiles.db.lock' file" "error"
     runCommand "chown nx:root '$NODE_ROOT/etc/profiles.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/profiles.db.lock' to '0600'" "error"
  fi

  if [ ! -f "$NODE_ROOT/etc/users.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/users.db.lock'" "Cannot create '$NODE_ROOT/etc/users.db.lock' file" "error"
     runCommand "chown nx:root '$NODE_ROOT/etc/users.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/users.db.lock' to 'nx:root'" "error"
  fi

  if [ -f "$LICENSE_FILE" ];
  then
    runCommand "chown nx:root '$LICENSE_FILE'" "Cannot change ownership for '$LICENSE_FILE'" "error"
    runCommand "chmod 0400 '$LICENSE_FILE'" "Cannot change permissions for '$LICENSE_FILE'" "error"
  fi

}

checkNXUsersFile () {
  if [ ! -f "$NODE_ROOT/etc/users.db" ];
  then
     runCommand "touch '$NODE_ROOT/etc/users.db'" "Cannot create file: $NODE_ROOT/etc/users.db" "error"
  fi
}

checkAdministratorsDb () {

  if [ ! -f "$NODE_ROOT/etc/administrators.db" ];
  then
    runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/administrators.db.sample' '$NODE_ROOT/etc/administrators.db'" "Cannot copy '$NODE_ROOT/etc/adminisrators.db.sample' to '$NODE_ROOT/etc/administrators.db'." "error"
  fi
}

checkNXConfiguration () {

  fixoldnxstat
  runCommand "chown nx:root '$NODE_ROOT/etc'" "Cannot set ownership attributes for '$NODE_ROOT/etc' to 'nx:root'" "error"
  runCommand "chown nx:root '$NODE_ROOT/etc/keys'" "Cannot set ownership attributes for '$NODE_ROOT/etc/keys' to 'nx:root'" "error"
  runCommand "chown nx:root '$NODE_ROOT/etc/keys/node.localhost.id_dsa'" "Cannot set ownership attributes for '$NODE_ROOT/etc/keys/node.localhost.id_dsa' to 'nx:root'" "error"

  runCommand "chown -R nx:root '$NODE_ROOT/home/nx'" "Cannot set ownership attributes for '$NODE_ROOT/home/nx' to 'nx:root'" "error"

  runCommand "chmod 0700 '$NODE_ROOT/home/nx'" "Cannot set permissions attributes for '$NODE_ROOT/home/nx' to '0700'" "error"
  runCommand "chown nx:root '$NODE_ROOT/var'" "Cannot set ownership attributes for '$NODE_ROOT/var' to 'nx:root'" "error"
  runCommand "chown nx:root '$NODE_ROOT/var/db'" "Cannot set ownership attributes for '$NODE_ROOT/var/db' to 'nx:root'" "error"
  runCommand "chown -R nx:root '$NODE_ROOT/var/db/closed'" "Cannot set ownership attributes for '$NODE_ROOT/var/db/closed' to 'nx:root'" "error"
  runCommand "chown -R nx:root '$NODE_ROOT/var/db/running'" "Cannot set ownership attributes for '$NODE_ROOT/var/db/running' to 'nx:root'" "error"
  runCommand "chown -R nx:root '$NODE_ROOT/var/db/failed'" "Cannot set ownership attributes for '$NODE_ROOT/var/db/failed' to 'nx:root'" "error"

  if [ -f $NODE_ROOT/var/num ];
  then
    runCommand "chown nx:root '$NODE_ROOT/var/num'" "Cannot set ownership attributes for '$NODE_ROOT/var/num'" "warn"
  fi

  runCommand "chown nx:root '$NODE_ROOT/etc/passwords.db'" "Cannot set ownership attributes for '$NODE_ROOT/etc/passwords.db' to 'nx:root'" "error"
  runCommand "chmod 0600 '$NODE_ROOT/etc/passwords.db'" "Cannot set permissions attributes for '$NODE_ROOT/etc/passwords.db' to '0600'" "error"
  if [ ! -f "$NODE_ROOT/etc/passwords.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/passwords.db.lock'" "Cannot create '$NODE_ROOT/etc/passwords.db.lock' file" "error"
  fi
  runCommand "chown nx:root '$NODE_ROOT/etc/passwords.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/passwords.db.lock' to 'nx:root'" "error"

  runCommand "chown nx:root '$NODE_ROOT/etc/users.db'" "Cannot set ownership attributes for '$NODE_ROOT/etc/users.db' to 'nx:root'" "error"
  runCommand "chmod 0600 '$NODE_ROOT/etc/users.db'" "Cannot set permissions attributes for '$NODE_ROOT/etc/users.db' to '0600'" "error"
  if [ ! -f "$NODE_ROOT/etc/users.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/users.db.lock'" "Cannot create '$NODE_ROOT/etc/users.db.lock' file" "error"
  fi
  runCommand "chown nx:root '$NODE_ROOT/etc/users.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/users.db.lock' to 'nx:root'" "error"

  runCommand "chown nx:root '$NODE_ROOT/etc/guests.db'" "Cannot set ownership attributes for '$NODE_ROOT/etc/guests.db' to 'nx:root'" "error"
  runCommand "chmod 0600 '$NODE_ROOT/etc/guests.db'" "Cannot set permissions attributes for '$NODE_ROOT/etc/guests.db' to '0600'" "error"
  if [ ! -f "$NODE_ROOT/etc/guests.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/guests.db.lock'" "Cannot create '$NODE_ROOT/etc/guests.db.lock' file" "error"
  fi
  runCommand "chown nx:root '$NODE_ROOT/etc/guests.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/guests.db.lock' to 'nx:root'" "error"

  runCommand "chmod 0600 '$NODE_ROOT/etc/administrators.db'" "Cannot set permissions attributes for '$NODE_ROOT/etc/administrators.db' to '0600'" "error"
  runCommand "chown nx:root '$NODE_ROOT/etc/administrators.db'" "Cannot set ownership attributes for '$NODE_ROOT/etc/administrators.db' to '0600'" "error"
  if [ ! -f "$NODE_ROOT/etc/administrators.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/administrators.db.lock'" "Cannot create '$NODE_ROOT/etc/administrators.db.lock' file" "error"
  fi
  runCommand "chown nx:root '$NODE_ROOT/etc/administrators.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/administrators.db.lock' to '0600'" "error"

  runCommand "chmod 0600 '$NODE_ROOT/etc/profiles.db'" "Cannot set permissions attributes for '$NODE_ROOT/etc/profiles.db' to '0600'" "error"
  runCommand "chown nx:root '$NODE_ROOT/etc/profiles.db'" "Cannot set ownership attributes for '$NODE_ROOT/etc/profiles.db' to '0600'" "error"
  if [ ! -f "$NODE_ROOT/etc/profiles.db.lock" ];
  then
     runCommand "touch '$NODE_ROOT/etc/profiles.db.lock'" "Cannot create '$NODE_ROOT/etc/profiles.db.lock' file" "error"
  fi
  runCommand "chown nx:root '$NODE_ROOT/etc/profiles.db.lock'" "Cannot set ownership attributes for '$NODE_ROOT/etc/profiles.db.lock' to '0600'" "error"


  if [ ! -f "$NODE_ROOT/etc/nodes.db" ];
  then  
    runCommand "touch $NODE_ROOT/etc/nodes.db" "Cannot create stopped nodes database" "warn"
  fi 
  runCommand "chown nx $NODE_ROOT/etc/nodes.db" "Cannot change ownership of file '$NODE_ROOT/etc/nodes.db'" "warn"

  if [ ! -f "$NODE_ROOT/var/db/broadcast" ];
  then  
    runCommand "touch $NODE_ROOT/var/db/broadcast" "Cannot initialize broadcast" "warn"
  fi 
  runCommand "chown nx $NODE_ROOT/var/db/broadcast" "Cannot change ownership of file '$NODE_ROOT/var/db/broadcast'" "warn"

  if [ -f "$LICENSE_FILE" ];
  then
    runCommand "chown nx:root '$LICENSE_FILE'" "Cannot change ownership for '$LICENSE_FILE'" "error"
    runCommand "chmod 0400 '$LICENSE_FILE'" "Cannot change permissions for '$LICENSE_FILE'" "error"
  fi

  if [ ! -f "$CONFIG_FILE" ];
  then
    printMsg "Creating configuration file: $CONFIG_FILE"
    if [ -f "$CONFIG_FILE.update" ];
    then
      runCommand "$CPCOMMAND -f '$CONFIG_FILE.update' '$CONFIG_FILE'" "Cannot copy '$CONFIG_FILE.update' to '$CONFIG_FILE'" "error"
    else
      if [ -f "$NODE_ROOT/etc/server-$system.cfg.sample" ];
      then
        runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/server-$system.cfg.sample' '$CONFIG_FILE'" "Cannot copy '$NODE_ROOT/etc/server-$system.cfg.sample' to '$CONFIG_FILE'" "error"
      else
        printMsg "Cannot create configuration file" "error"
        exit 1
      fi
    fi
  fi
}

checkNXkeys () {
  
  if [ ! -f "$NODE_ROOT/etc/keys/node.localhost.id_dsa" ];
  then
    printMsgNoDot "Installation of NX server is broken: " "error" 
    printMsgNoDot "Missing $NODE_ROOT/etc/keys/node.localhost.id_dsa ssh key file!" "error"
    printMsg "Please uninstall and install again" "error"
    printMsg "Bye"
    echo ""
    exit 1
  fi
  
  if [ ! -f "$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub" ];
  then
    printMsgNoDot "Installation of NX server is broken:" "error"
    printMsgNoDot "Missing $NODE_ROOT/etc/keys/node.localhost.id_dsa.pub ssh key file!" "error"
    printMsg "Please uninstall and install again" "error"
    printMsg "Bye"
    echo ""
    exit 1
  fi
}

resetNXConfigServer () {

  if [ -f "$CONFIG_FILE" ];
  then
    printMsg "Saving configuration file to: $CONFIG_FILE.backup"

    runCommand "$MVCOMMAND -f '$CONFIG_FILE' '$CONFIG_FILE.backup'" "Cannot move '$CONFIG_FILE' file to '$CONFIG_FILE.backup'" "error"
  fi

  if [ "$system" != "solaris" ];
  then
    if [ -f "$NODE_ROOT/etc/passwords.db" ];
    then
      printMsg "Saving passwords DB to: $NODE_ROOT/etc/passwords.db.backup"

      runCommand "$MVCOMMAND -f '$NODE_ROOT/etc/passwords.db' '$NODE_ROOT/etc/passwords.db.backup'" "Cannot move '$NODE_ROOT/etc/passwords.db' file to '$NODE_ROOT/etc/passwords.db.backup'" "error" 
    fi
  fi

  if [ -f "$NODE_ROOT/etc/users.db" ];
  then
    printMsg "Saving users DB to: $NODE_ROOT/etc/users.db.backup" 
    runCommand "$MVCOMMAND -f '$NODE_ROOT/etc/users.db' '$NODE_ROOT/etc/users.db.backup'" "Cannot move '$NODE_ROOT/etc/users.db' file to '$NODE_ROOT/etc/users.db.backup'" "error"
  fi

  if [ -f "$NODE_ROOT/etc/administrators.db" ];
  then
    printMsg "Saving administrators DB to: $NODE_ROOT/etc/administrators.db.backup"
    runCommand "$MVCOMMAND -f '$NODE_ROOT/etc/administrators.db' '$NODE_ROOT/etc/administrators.db.backup'" "Cannot move '$NODE_ROOT/etc/administrators.db' file to '$NODE_ROOT/etc/administrators.db.backup'" "error"
  fi

  if [ -f "$NODE_ROOT/etc/profiles.db" ];
  then
    printMsg "Saving profiles DB to: $NODE_ROOT/etc/profiles.db.backup"
    runCommand "$MVCOMMAND -f '$NODE_ROOT/etc/profiles.db' '$NODE_ROOT/etc/profiles.db.backup'" "Cannot move '$NODE_ROOT/etc/profiles.db' file to '$NODE_ROOT/etc/profiles.db.backup'" "error"
  fi

  if [ -f "$NODE_ROOT/etc/guests.db" ];
  then
    printMsg "Saving guests DB to: $NODE_ROOT/etc/guests.db.backup"
    runCommand "$MVCOMMAND -f '$NODE_ROOT/etc/guests.db' '$NODE_ROOT/etc/guests.db.backup'" "Cannot move '$NODE_ROOT/etc/guests.db' file to '$NODE_ROOT/etc/guests.db.backup'" "error"
  fi

 if [ -f "$NODE_ROOT/var/db/broadcast" ];
  then
    cleanNXDb
  fi

  runCommand "chown -R root:root $NODE_ROOT/etc" "Cannot set ownership of '$NODE_ROOT/etc' directory." "warn"
  runCommand "chown -R root:root $NODE_ROOT/var" "Cannot set ownership of '$NODE_ROOT/var' directory." "warn"

  if [ -f "$NODE_ROOT/home/nx/.ssh/authorized_keys2" ];
  then
    command="$RMCOMMAND -f $NODE_ROOT/home/nx/.ssh/authorized_keys2"
    printMsg "Command: $command" "cmd"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "warn"
      printMsg "Cannot delete '$NODE_ROOT/home/nx/.ssh/authorized_keys2' file" "warn"
      printMsg "The user: nx will be able login using its own public key" "warn"
    else
      printMsg "$outCommand" "cmd"
      printMsg "Result: OK" "cmd"
    fi
  fi

  if [ -f "$NODE_ROOT/home/nx/.ssh/authorized_keys" ];
  then
    command="$RMCOMMAND -f $NODE_ROOT/home/nx/.ssh/authorized_keys"
    printMsg "Command: $command" "cmd"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "warn"
      printMsg "Cannot delete file: $NODE_ROOT/home/nx/.ssh/authorized_keys" "warn"
      printMsg "The user: nx will be able login using its own public key" "warn"
    else
      printMsg "$outCommand" "cmd"
      printMsg "Result: OK" "cmd"
    fi
  fi
  runCommand "$RMCOMMAND -f $NODE_ROOT/home/nx/.ssh/known_hosts" "Cannot delete '$NODE_ROOT/home/nx/.ssh/known_hosts' file" "warn"
}

fixEnableStatistics() {

  sed 's/EnableStatisticsDB/EnableStatistics/g' $CONFIG_FILE > $CONFIG_FILE.tmp
  runCommand "$MVCOMMAND -f $CONFIG_FILE.tmp $CONFIG_FILE" "Cannot move '$CONFIG_FILE.tmp' file to '$CONFIG_FILE'." "error"
}

fixoldconffileServer() {

  #printMsgNoDot "Checking NX server configuration using the"
  #printMsg "$CONFIG_FILE file"
  fixEnableStatistics

command="grep UserId $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Set the User Identifier (UID) number for NX users. If an empty value
# is specified, the NX server will create the account with the default 
# value set on the system.
#
#UserId = \"10\"
" >> $CONFIG_FILE
  fi

  command="grep UserGroup $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Set the Group Identifier (GID) for NX users. If an empty value is
# specified, the NX server will create the account with the default
# value set on the system.
#
#UserGroup = \"users\"
" >> $CONFIG_FILE
  fi

  command="grep UserHome $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Set the home directory for NX users. If an empty value is specified,
# the NX server will create the user's home in the default directory
# set on the system.
#
#UserHome = \"/home\"
" >> $CONFIG_FILE
  fi

  command="grep EnableStatistics $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable statistics:
#
# 1: Enabled. Enable the production of NX statistics.
#
# 0: Disabled. Disable the production of NX statistics.
#
# Run the nxstat daemon in background. This daemon can be used to
# produce statistics about the NX services and the node host machine
# either for localhost and any of the available nodes when the load
# balancing is enabled. This requires that the nxsensor daemon is
# started on each of the node machines. 
#
#EnableStatistics = \"0\"
" >> $CONFIG_FILE
  fi

  command="grep ServerSensorPort $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify the port where the server will contact the nxsensor daemons
# to collect the statistics.
#
#ServerSensorPort = \"19250\"
" >> $CONFIG_FILE

  fi

  command="grep EnableNodeMonitoring $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable monitoring the NX Node host machines when load-
# balancing is enabled in the NX Advanced Server configuration.
#
# 1: Enabled. Enable starting of the NX Server daemon.
#
# 0: Disabled. Disable starting of the NX Server daemon.
#
#EnableNodeMonitoring = \"0\"
" >> $CONFIG_FILE

  fi

command="grep NodeResponseTimeout $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Set for how long the NX server daemon has to wait for a reply from
# the node machine before considering that this host is unreachable.
# The default value, 10, let NX server daemon to wait for 10 seconds.
#
#NodeResponseTimeout = \"10\"
" >> $CONFIG_FILE
  fi

  command="grep EnableUserProfile $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable support for user profiles:
#
# 1: Enabled. The NX server allows the NX session to start
#    according to the set of rules specified for the system
#    or on a per-user basis.
#
# 0: Disabled. The NX server starts the session without apply-
#    ing any rules.
#
# The administrator can configure access to applications and nodes
# by creating a specific profile for the NX system, which will be
# applied to any user starting a session on this server, or by def-
# ining profiles on a per-user basis. Any profile consists of a set
# of rules specifying what the user can or can't do in the session.
#
#EnableUserProfile = \"0\"
" >> $CONFIG_FILE
  fi

command="grep EnableClipboard $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable clipboard:
#
# client: The content copied on the client can be pasted inside the
#         NX session.
#
# server: The content copied inside the NX session can be pasted
#         on the client.
#
# both:   The copy&paste operations are allowed between both the
#         client and the NX session and viceversa.
#
# none:   The copy&paste operations between the client and the NX
#         session are never allowed.
#
#EnableClipboard = \"both\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptBeforeLogin $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# the user logs in. The script can accept remote IP of the user's
# machine as its input.
#
# E.g. UserScriptBeforeLogin = \"/tmp/nxscript/script.sh\"
#
#UserScriptBeforeLogin = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterLogin $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after
# the user logs in. The script can accept username as its input.
#
#UserScriptAfterLogin = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptBeforeSessionStart $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# the session start-up. The script can accept session ID, username
# node host and node port as its input.
#
#UserScriptBeforeSessionStart = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterSessionStart $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after the
# session start-up. The script can accept session ID, username, node
# host and node port as its input.
#
#UserScriptAfterSessionStart = \"\"
" >> $CONFIG_FILE
  fi


command="grep UserScriptBeforeSessionClose $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# the session is closed. The script can accept session ID, username,
# node host and node port as its input.
#
#UserScriptBeforeSessionClose = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterSessionClose $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after the
# session is closed. The script can accept session ID, username, node
# host and node port as its input.
#
#UserScriptAfterSessionClose = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptBeforeSessionReconnect $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# the session is reconnected. The script can accept session ID user-
# name, node host and node port as its input.
#
#UserScriptBeforeSessionReconnect = \"\"
" >> $CONFIG_FILE
  fi


command="grep UserScriptAfterSessionReconnect $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after the
# session is reconnected. The script can accept session ID username
# node host and node port as its input.
#
#UserScriptAfterSessionReconnect = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptBeforeSessionSuspend $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# the session is suspended. The script can accept session ID, user-
# name, node host and node port as its input.
#
#UserScriptBeforeSessionSuspend = \"\"
" >> $CONFIG_FILE
  fi


command="grep UserScriptAfterSessionSuspend $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after
# the session is suspended. The script can accept session ID, user
# name, node host and node port as its input.
#
#UserScriptAfterSessionSuspend = \"\"
" >> $CONFIG_FILE
  fi


command="grep UserScriptBeforeSessionFailure $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# session failure. The script can accept session ID username, node
# host and node port as its input.
#
#UserScriptBeforeSessionFailure = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterSessionFailure $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after
# session failure. The script can accept session ID username, node
# host and node port as its input.
#
#UserScriptAfterSessionFailure = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptBeforeCreateUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# NX Server creates the new account. The script can accept username
# as its input.
#
#UserScriptBeforeCreateUser = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterCreateUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after
# NX Server has created the new account. The script can accept user-
# name as its input.
#
#UserScriptAfterCreateUser = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptBeforeDeleteUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# NX Server removes the account. The script can accept username as
# its input.
#
#UserScriptBeforeDeleteUser = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterDeleteUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after
# NX Server has removed the account. The script can accept username
# as its input.
#
#UserScriptAfterDeleteUser = \"\"
" >> $CONFIG_FILE
 fi


command="grep UserScriptBeforeDisableUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# NX Server disables the user. The script can accept username as its
# input.
#
#UserScriptBeforeDisableUser = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterDisableUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after
# NX Server has disabled the user. The script can accept username
# as its input.
#
#UserScriptAfterDisableUser = \"\"
" >> $CONFIG_FILE
  fi


command="grep UserScriptBeforeEnableUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed before
# NX Server enables the user. The script can accept username as its
# input.
#
#UserScriptBeforeEnableUser = \"\"
" >> $CONFIG_FILE
  fi

command="grep UserScriptAfterEnableUser $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify absolute path of the custom script to be executed after
# NX Server has enabled the user. The script can accept username
# as its input.
#
#UserScriptAfterEnableUser = \"\"
" >> $CONFIG_FILE
  fi

command="grep EnableSessionShadowing $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Allow session shadowing on this server:
#
# 1: Enabled. User can require to attach to an already running
#    session. The session owner has to accept connection.
#
# 0: Disabled. Session shadowing is forbidden.
#
#EnableSessionShadowing = \"1\"
" >> $CONFIG_FILE
  fi


command="grep EnableInteractiveSessionShadowing $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Allow session shadowing in interactive mode:
#
# 1: Enabled. User attaching to the session can interact with
#    the session.
#
# 0: Disabled. The session is shadowed in view-only mode. User 
#    attaching to the session can't interact with the session.
#
#EnableInteractiveSessionShadowing = \"1\"
" >> $CONFIG_FILE
  fi


command="grep EnableSessionShadowingAuthorization $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable NX server requiring authorization to the owner
# of the NX session before sharing the session.
#
# 1: Enabled. NX server asks for authorization to the owner
#    of the master session before trying to share the session.
#
# 0: Disabled. NX server tries to share the NX session without
#    the need of any authorization from the owner of the master
#    desktop.
#
#EnableSessionShadowingAuthorization = \"1\"
" >> $CONFIG_FILE
  fi


command="grep EnableDesktopSharing $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Allow desktop sharing on this server:
#
# 1: Enabled. User can require to attach to the native display
#    of the nodes. The desktop's owner has to accept connection.
#
# 0: Disabled. Desktop sharing is forbidden.
#
#EnableDesktopSharing = \"1\"
" >> $CONFIG_FILE
  fi

  command="grep EnableFullDesktopSharing $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Allow the NX user to connect to a desktop owned by a user who is
# not an NX user:
#
# 1: Enabled. Allow an NX user to connect to a desktop owned
#    by a user who is not an NX user. This requires running a
#    privileged script as root and will work only if the node.
#    is the same machine where NX server is running.
#
# 0: Disabled. An NX user can connect only to a desktop owned
#    by an NX user when EnableDesktopSharing is enabled.
#
#EnableFullDesktopSharing = \"0\"
" >> $CONFIG_FILE
  fi



command="grep EnableInteractiveDesktopSharing $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Allow desktop sharing in interactive mode:
#
# 1: Enabled. User attaching to the desktop can interact with
#    the session.
#
# 0: Disabled. The session is shadowed in view-only mode. User
#    attaching to the desktop can't interact with the session.
#
#EnableInteractiveDesktopSharing = \"0\"
" >> $CONFIG_FILE
  fi


command="grep EnableDesktopSharingAuthorization $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable NX server requiring authorization to the owner
# of the desktop before sharing the session.
#
# 1: Enabled. NX server asks for authorization to the owner
#    of the desktop.
#
# 0: Disabled. NX server tries to share the native display
#    without the need of any authorization from the owner
#    of the desktop.
#
#EnableDesktopSharingAuthorization = \"1\"
" >> $CONFIG_FILE
  fi

  command="grep EnableSystemDesktopSharingAuthorization $CONFIG_FILE" 
   outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable NX server requiring authorization before sharing
# the session either when the X server is running as root or gdm.
#
# 1: Enabled. NX server needs authorization to proceed with
#    sharing the session.
#
# 0: Disabled. NX server tries to share the native display
#    without the need for any authorization. Sharing the
#    session is also possible when a user is not logged
#    on to the local desktop.
# 
#EnableSystemDesktopSharingAuthorization = \"1\"
"  >> $CONFIG_FILE
  fi


  command="grep EnableGuestQuota $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then

    echo "#
# Allow the server to set disk quota for the guest accounts:
#
# 1: Enabled. When a new guest account is created on the system,
#    the server will set the disk quota for this user.
#
# 0: Disabled. No restrictions on the amount of disk space used
#    by each guest user are applied.
#
#EnableGuestQuota = \"0\"

#
# Specify the username of the account to be used as a protoype for
# propagating its disk quota settings to all the new guest accounts.
# If the softlimit or the hardlimit on either the inode or the disk
# block are set, they will override the settings applied to the user
# prototype.
#
#GuestQuotaProtoname = \"protoguest\"

#
# Specify the maximum amount of disk space available for each of the
# guest users, checked as number of inodes. This limit can be exceeded
# for the grace period.
#
#GuestQuotaInodeSoftlimit = \"0\"

#
# Specify the absolute maximum amount of disk space available for
# each of the guest users, checked as number of inodes. Once this
# limit is reached, no further disk space can be used.
#
#GuestQuotaInodeHardlimit = \"0\"

#
# Specify the maximum amount of disk space available for each of the
# guest users, checked as number of disk blocks consumed. This limit
# can be exceeded for the grace period.
#
#GuestQuotaBlockSoftlimit = \"0\"

#
# Specify the absolute maximum amount of disk space available for each
# of the guest users, checked as number of disk blocks consumed. Once
# this limit is reached, no further disk space can be used.
#
#GuestQuotaBlockHardlimit = \"0\"

#
# Specify the grace period, expressed in seconds, during which the
# soft limit, set in the GuestQuotaInodeSoftlimit key may be
# exceeded.
#
#GuestQuotaInodeGracePeriod = \"0\"

#
# Specify the grace period, expressed in seconds, during which the
# soft limit, set in the GuestQuotaBlockSoftlimit key may be
# exceeded.
#
#GuestQuotaBlockGracePeriod = \"0\"

#
# Specify a list of comma-separated filesystem names or devices to
# which the disk quota restrictions will be applied. The default
# value is 'all' which corresponds to applying the disk quota limits
# to all the filesystems having disk quota enabled.
#
#GuestQuotaFilesystems = \"all\"
" >> $CONFIG_FILE

  fi

}

fixoldpasswdfile () {

  if [ -f "$NODE_ROOT/etc/passwd" ];
    then
     runCommand "$MVCOMMAND '$NODE_ROOT/etc/passwd' '$NODE_ROOT/etc/passwords.db'" "Cannot move '$NODE_ROOT/etc/passwd' file to '$NODE_ROOT/etc/passwords.db'" "error"
     runCommand "echo >> '$NODE_ROOT/etc/passwords.db'" "Cannot create '$NODE_ROOT/etc/passwords.db' file"
  fi

  if [ -f "$NODE_ROOT/etc/passwords" ];
    then
     runCommand "$MVCOMMAND '$NODE_ROOT/etc/passwords' '$NODE_ROOT/etc/passwords.db'" "Cannot move '$NODE_ROOT/etc/passwords' file to '$NODE_ROOT/etc/passwords.db'" "error"
     runCommand "echo >> '$NODE_ROOT/etc/passwords.db'" "Cannot create '$NODE_ROOT/etc/passwords.db' file"
  fi
}

fixoldusersfile () {

  if [ -f "$NODE_ROOT/etc/users" ];
    then
     runCommand "$MVCOMMAND '$NODE_ROOT/etc/users' '$NODE_ROOT/etc/users.db'" "Cannot move '$NODE_ROOT/etc/users' file to '$NODE_ROOT/etc/users.db'" "error"
     runCommand "echo >> '$NODE_ROOT/etc/users.db'" "Cannot create '$NODE_ROOT/etc/users.db' file"
  fi
}

fixoldkeyfile () {

  if [ -f "$NODE_ROOT/home/nx/.ssh/client.id_dsa.key" ];
  then
    runCommand "$RMCOMMAND $NODE_ROOT/home/nx/.ssh/client.id_dsa.key" "Cannot removed '$NODE_ROOT/home/nx/.ssh/client.id_dsa.key' file"
  fi

  if [ -f "$NODE_ROOT/etc/users.id_dsa" ];
  then
    printMsg "Found file $NODE_ROOT/etc/users.id_dsa" "warn"
    printMsg "Skipping generation keys for NX users authentication" "warn"
    runCommand "$MVCOMMAND '$NODE_ROOT/etc/users.id_dsa' '$NODE_ROOT/etc/keys/node.localhost.id_dsa'" "Cannot move '$NODE_ROOT/etc/users.id_dsa' file to '$NODE_ROOT/etc/keys/node.localhost.id_dsa'" "error"
  fi
  
  if [ -f "$NODE_ROOT/etc/users.id_dsa.pub" ];
  then
    runCommand "$MVCOMMAND '$NODE_ROOT/etc/users.id_dsa.pub' '$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub'" "Cannot move '$NODE_ROOT/etc/users.id_dsa.pub' file to '$NODE_ROOT/etc/keys/node.localhost.id_dsa.pub'" "error"
  fi

}

fixlicensefile () {

  if [ -f "$NODE_ROOT/etc/key.txt" ];
  then
    runCommand "$MVCOMMAND '$NODE_ROOT/etc/key.txt' '$LICENSE_FILE'" "Cannot move '$NODE_ROOT/etc/key.txt' file to '$LICENSE_FILE'" "error"
  fi
}

upgradeLicenseFile () {

  if [ -f "$LICENSE_FILE" ];
  then
    tmp1=`$AWKCOMMAND  '/^Product Id/ {print $3}' $LICENSE_FILE.sample 2>/dev/null`
    if [ "x$tmp1" = "xLFE" -o "x$tmp1" = "xSFE" ];
    then
      tmp2=`$AWKCOMMAND  '/^Product Id/ {print $3}' $LICENSE_FILE 2>/dev/null`
      if [ "x$tmp2" = "xLDS" -o "x$tmp2" = "xSDS" ];
      then
        validateLicenseFile
        installLicenseFile
      else
        removeLicenseSampleFile
      fi
    else
      removeLicenseSampleFile
    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" ]
  then
    validateLicenseFile
    installLicenseFile
    return 0
  fi

  if [ "$SUBSCRIPTION" = "Evaluation" ]
  then
    validateLicenseFile
    installLicenseFile
    return 0
  fi
}

installLicenseFile () {

  if [ -f "$LICENSE_FILE.sample" ];
  then
    if [ -f "$LICENSE_FILE" ];
    then
      runCommand "$RMCOMMAND -f $LICENSE_FILE" "Cannot delete '$LICENSE_FILE'" "error"
    fi
    runCommand "$MVCOMMAND '$LICENSE_FILE.sample' '$LICENSE_FILE'" "Cannot move '$LICENSE_FILE.sample' file to '$LICENSE_FILE'" "error"
  fi

  if [ -f "$LICENSE_FILE" ];
  then
    runCommand "chown nx:root '$LICENSE_FILE'" "Cannot change ownership for '$LICENSE_FILE'" "error"
    runCommand "chmod 0400 '$LICENSE_FILE'" "Cannot change permissions for '$LICENSE_FILE'" "error"
  fi
}

validateLicenseFile () {
  if [ -f "$LICENSE_FILE.sample" ];
  then
    runCommand "$NXSHELL --validate" "Cannot validate license file"
  fi
}

validateNodeLicenseFile () {

  if [ -f "$LICENSE_FILE" ];
  then
    if [ -f "$NODE_LICENSE_FILE" ];
    then
      tmp1=`$AWKCOMMAND  '/^Product Id/ {print $3}' $LICENSE_FILE 2>/dev/null`
      if [ "x$tmp1" = "xLFE" -o "x$tmp1" = "xSFE" ];
      then
        tmp2=`$AWKCOMMAND  '/^Product Id/ {print $3}' $NODE_LICENSE_FILE 2>/dev/null`
        if [ "x$tmp2" = "xLDSN" -o "x$tmp2" = "xSDSN" ];
        then
          return;
        fi
      fi
    fi
  fi

  if [ -f "$LICENSE_FILE" ];
  then
    if [ -f "$NODE_LICENSE_FILE" ];
    then
      runCommand "$NXSHELL --validatenode" "Cannot validate node license file"
    fi
  fi
}

removeLicenseSampleFile () {

  if [ -f "$LICENSE_FILE.sample" ];
  then
    runCommand "$RMCOMMAND -f $LICENSE_FILE.sample" "Cannot delete '$LICENSE_FILE.sample'" "error"
  fi

}

fixoldnxstat () {

  if [ -d "$NODE_ROOT/var/db/nxstat" ];
  then
    if [ ! -d "$NXSTATISTICS" ];
    then
      printMsg "Found $NODE_ROOT/var/db/nxstat. Moved ' $NODE_ROOT/var/db/nxstat' directory to: ' $NXSTATISTICS' "
      runCommand "$MVCOMMAND -f '$NODE_ROOT/var/db/nxstat' '$NXSTATISTICS' " "Cannot move: '$NODE_ROOT/var/db/nxstat' dir to: '$NXSTATISTICS'" "error"
    fi
  fi

}

fixoldnxhome () {

  if [ -d "$NODE_ROOT/home/.ssh" ];
  then
    runCommand "(cd $NODE_ROOT/home/nx && tar cf - . ) | (cd $NODE_ROOT/home && tar xfB -)" "Cannot copy '$NODE_ROOT/home/nx' directory to '$NODE_ROOT/home'" "error"
    runCommand "$RMCOMMAND -rf $NODE_ROOT/home/nx" "Cannot delete '$NODE_ROOT/home/nx' directory" "error"
    if [ -d "$NODE_ROOT/nxhome" ];
    then
      runCommand "(cd $NODE_ROOT/home && tar cf - . ) | (cd $NODE_ROOT/nxhome && tar xfB -)" "Cannot copy '$NODE_ROOT/home' directory to '$NODE_ROOT/nxhome'" "error"
      runCommand "$RMCOMMAND -rf $NODE_ROOT/home" "Cannot delete '$NODE_ROOT/home' directory" "error"
      runCommand "mkdir $NODE_ROOT/home" "Cannot create '$NODE_ROOT/home' directory" "error"
      runCommand "chmod 0755 $NODE_ROOT/home" "Cannot change permissions of '$NODE_ROOT/home' directory" "error"
      runCommand "$MVCOMMAND $NODE_ROOT/nxhome $NODE_ROOT/home/nx" "Cannot move '$NODE_ROOT/nxhome' directory to '$NODE_ROOT/home/nx'" "error"
    else
      runCommand "$MVCOMMAND $NODE_ROOT/home $NODE_ROOT/home.tmp" "Cannot move '$NODE_ROOT/home' directory to '$NODE_ROOT/home.tmp'" "error"
      runCommand "$RMCOMMAND -rf $NODE_ROOT/home" "Cannot remove '$NODE_ROOT/home'" "error"
      runCommand "mkdir $NODE_ROOT/home" "Cannot create '$NODE_ROOT/home' directory" "error"
      runCommand "$MVCOMMAND $NODE_ROOT/home.tmp $NODE_ROOT/home/nx" "Cannot move '$NODE_ROOT/home.tmp' directory to '$NODE_ROOT/home/nx'" "error"
      runCommand "usermod -d $NODE_ROOT/home/nx nx" "Cannot change home directory for user: nx" "error"
      runCommand "chown -R nx:root $NODE_ROOT/home/nx" "Cannot change ownership of '$NODE_ROOT/home/nx' directory" "error"
      runCommand "chmod 0700 $NODE_ROOT/home/nx" "Cannot set permissions of '$NODE_ROOT/home/nx' directory" "error"
      runCommand "chmod 0700 $NODE_ROOT/home/nx/.ssh" "Cannot set permissions of '$NODE_ROOT/home/nx/.ssh' directory" "error"
    fi
  else
    if [ -d "$NODE_ROOT/nxhome" ];
    then
      runCommand "(cd $NODE_ROOT/home/nx && tar cf - . ) | (cd $NODE_ROOT/nxhome && tar xfB -)" "Cannot copy '$NODE_ROOT/home/nx' directory to '$NODE_ROOT/nxhome'" "error"
      runCommand "$RMCOMMAND -rf $NODE_ROOT/home" "Cannot remove '$NODE_ROOT/home' directory" "error"
      runCommand "mkdir $NODE_ROOT/home" "Cannot create directory '$NODE_ROOT/home'" "error"
      runCommand "chmod 0755 $NODE_ROOT/home" "Cannot change permissions of '$NODE_ROOT/home' directory" "error"
      runCommand "$MVCOMMAND $NODE_ROOT/nxhome $NODE_ROOT/home/nx" "Cannot move '$NODE_ROOT/nxhome' directory to '$NODE_ROOT/home/nx'" "error"
      runCommand "usermod -d $NODE_ROOT/home/nx nx" "Cannot change home directory for  user: nx" "error"
      runCommand "chown -R nx:root $NODE_ROOT/home/nx" "Cannot change ownership of '$NODE_ROOT/home/nx' directory" "error"
      runCommand "chmod 0700 $NODE_ROOT/home/nx" "Cannot set permissions of '$NODE_ROOT/home/nx' directory" "error"
      runCommand "chmod 0700 $NODE_ROOT/home/nx/.ssh" "Cannot set permissions of '$NODE_ROOT/home/nx/.ssh' directory" "error"
    fi
  fi
}

cleanRestrictedDirectory () {

  if [ -d "$NODE_ROOT/restricted" ];
  then
    if [ -f "$NODE_ROOT/restricted/nxaddprinter.sh" ];
    then
      runCommand "$RMCOMMAND -f $NODE_ROOT/restricted/nxaddprinter.sh" "Cannot remove $NODE_ROOT/restricted/nxaddprinter.sh" "cmd"
    fi
    if [ -f "$NODE_ROOT/restricted/nxtmpperm.sh" ];
    then
      runCommand "$RMCOMMAND -f $NODE_ROOT/restricted/nxtmpperm.sh" "Cannot remove $NODE_ROOT/restricted/nxtmpperm.sh" "cmd"
    fi
    runCommand "rmdir $NODE_ROOT/restricted" "Cannot remove directory $NODE_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 "$NODE_ROOT/share/$tmpfile" ];
    then
      command="$RMCOMMAND -f $NODE_ROOT/share/$tmpfile"
      printMsg "Command: $command" "cmd"
      outCommand=`/bin/bash -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 "$NODE_ROOT/share/$tmpdir" ];
    then
      command="$RMCOMMAND -rf $NODE_ROOT/share/$tmpdir"
      printMsg "Command: $command" "cmd"
      outCommand=`/bin/bash -c "$command" 2>&1`
      if [ "$?" != 0 ];
      then
        printMsg "$outCommand" "cmd"
      else
        printMsg "$outCommand" "cmd"
        printMsg "Result: OK" "cmd"
      fi
    fi
  done
}

copySessionHistory () {

  if [ -d "$NODE_ROOT/var/finishedSession" ];
  then
   runCommand "$MVCOMMAND '$NODE_ROOT/var/finishedSession/*' '$NODE_ROOT/var/db/closed'" "Cannot archiving session history" "warn"
  fi

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

cleanNXDb () {

  if [ -f "$NODE_ROOT/var/sessions/.counter" ];
  then
    runCommand "$RMCOMMAND -f '$NODE_ROOT/var/sessions/.counter'" "Cannot remove '$NODE_ROOT/var/sessions/.counter' file"
  fi

  if [ -f "$NODE_ROOT/var/db/broadcast" ];
  then
    runCommand "$RMCOMMAND -f '$NODE_ROOT/var/db/broadcast'" "Cannot remove '$NODE_ROOT/var/db/broadcast' file"
  fi

  if [ -d "$NODE_ROOT/var/db/running" ];
  then
    if [ -f "$NODE_ROOT/var/db/running/display{last}" ];
    then
      runCommand "$RMCOMMAND -f '$NODE_ROOT/var/db/running/display{last}'" "Cannot remove '$NODE_ROOT/var/db/running/display{last}' file"
    fi
    command="$RMCOMMAND -f $NODE_ROOT/var/db/running/session*"
    printMsg "Command: $command" "cmd"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "cmd"
    else
      printMsg "$outCommand" "cmd"
      printMsg "Result: OK" "cmd"
    fi

  fi

  if [ -d "$NODE_ROOT/var/db/failed" ];
  then
    command="$RMCOMMAND -f $NODE_ROOT/var/db/failed/session*"
    printMsg "Command: $command" "cmd"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "cmd"
    else
      printMsg "$outCommand" "cmd"
      printMsg "Result: OK" "cmd"
    fi
  fi

  if [ -d "$NODE_ROOT/var/db/closed" ];
  then
    command="$RMCOMMAND -f $NODE_ROOT/var/db/closed/session*"
    printMsg "Command: $command" "cmd"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ "$?" != 0 ];
    then
      printMsg "$outCommand" "cmd"
    else
      printMsg "$outCommand" "cmd"
      printMsg "Result: OK" "cmd"
    fi
  fi

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

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

checkSSHD () {
  procedure=$1
  if [ "x$procedure" = "x" ];
  then
    procedure="install"
  fi

  tmp=`$AWKCOMMAND -F'"' '/^SSHDPort/ {print $2}' $CONFIG_FILE 2>/dev/null`
  if [ "x$tmp" != "x" ];
  then
    SSHDPort=$tmp
  fi
    getHello=`LD_LIBRARY_PATH="$NODE_ROOT/lib:$LD_LIBRARY_PATH" $NODE_ROOT/bin/nxssh -nx -l nx -p $SSHDPort -i $NODE_ROOT/share/keys/server.id_dsa.key -T -x -2 -o 'RhostsAuthentication no' -o 'PasswordAuthentication no' -o 'RSAAuthentication yes' -o 'RhostsRSAAuthentication no' -o 'StrictHostKeyChecking no' 127.0.0.1 < /dev/null 2>&1`

  resultNXssh=$?
  result=`echo "$getHello" | grep -c "NX> 105" 2>&1`
  if [ $? != 0 ];
  then
    if [ $resultNXssh -ne $NXSSH_RCODE ];
    then
      tmp=`echo "$getHello" | grep -v "NX>" 2>&1`
      tmp2=`printf "%.4s" "$tmp"`
      if [ "$tmp2" = "ssh:" ];
      then
        printMsgNoDot "Error when trying to connect to NX 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 NX Server and" "warn"
        printMsgNoDot "Node accordingly. More information is available on the NoMachine" "warn"
        printMsgNoDot "Knowledge Base at: http://www.nomachine.com/kb/index.php" "warn"
      elif [ -f "$FILE_AUTHORIZED_KEYS" ];
      then 
        printMsgNoDot "Error when trying to connect to NX server, error is:" "warn"
        printMsg "$tmp" "warn"
        printMsgNoDot "nxsetup cannot validate the sanity of the current installation:" "warn"
        printMsg "the current system or NX 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 NX server and the" "warn"
        printMsg "NX client packages then install them again" "warn"
        printMsgNoDot "Search also the NoMachine Knowledge Base at the URL below:" "warn"
        printMsgNoDot "http://www.nomachine.com/kb" "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 NX server, error is:" "log"
        printMsg "$tmp" "log"
        printMsg "NX server is stopped. Please start NX server: $NXSHELL --start" "log"
      fi
    else
      result=`echo "$getHello" | grep -c "NX>" 2>&1`
      if [ $? != 0 ];
      then
        printMsgNoDot "Error when trying to connect to NX server, error is:" "warn"
        printMsg "$getHello" "warn"
        printMsgNoDot "nxsetup cannot validate the sanity of the current installation:" "warn"
        printMsg "the current system or NX 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 NX server and the" "warn"
        printMsg "NX client packages then install them again" "warn"
        printMsgNoDot "Search also the NoMachine Knowledge Base at the URL below:" "warn"
        printMsgNoDot "http://www.nomachine.com/kb" "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
}

printusage () {
  
  echo
  echo "Usage: `basename $0` ACTION"
  echo
  echo "Actions:"
  echo
  echo "--install        {SYSTEM}   Run the NX server install procedure for the"
  echo "                            specified system or distribuition"
  echo 
  echo "--update         {SYSTEM}   Run the NX server update procedure for the"
  echo "                            specified system or distribution"
  echo 
  echo "--uninstall                 Run the NX server uninstall procedure for the"
  echo "                            specified system or distribution "
  echo
  echo "--pre-uninstall             Disable access to new NX sessions, terminate"
  echo "                            sessions and reset the session DBs."
  echo 
  echo "--keygen                    Generate a new pair of SSH keys. After run-"
  echo "                            ning this procedure, the NX clients will use"
  echo "                            the key: $NODE_ROOT/share/keys/default.id_dsa.key"
  echo "                            to connect to this NX server."
  echo 
  echo "--help                      Show this message"
  echo
  echo "The specified SYSTEM must be one of the following operating systems,"
  echo "or none. In the latter case the NX setup will try to autodetect the"
  echo "system or will choose the layout that better resembles one of the"
  echo "known systems."
  echo
  echo "       redhat       RedHat 7.3, 8.0, 9.0, AS, ES, etc."
  echo "       suse         SuSE 7.3, 8.x, 9.x, etc."
  echo "       mandrake     Mandrake 9.2 10.x, etc."
  echo "       debian       Debian Woody 3.0, Unstable, Ubuntu, etc."
  echo "       solaris      Sun Solaris 8.0, 9.0, 10.0, etc."
  echo "       fedora       Fedora Core 1, 2, 3, 4, 5, etc. "

  echo "$errMsg"
  
  exit $E_WRONGARGS
}

if [ -f /etc/bash.bashrc ];
then
  rcBash="/etc/bash.bashrc"
else
  rcBash="/etc/bashrc"
fi

if [ ! -f $rcBash ];
then
  rcBash="/etc/profile"
fi

if [ -f /etc/csh.cshrc ];
then 
  rcCsh="/etc/csh.cshrc"
else
  rcCsh="/etc/csh.login"
fi

action="$1"

ARGS=1
E_WRONGARGS=65
FILE_AUTHORIZED_KEYS="$NODE_ROOT/home/nx/.ssh/authorized_keys2"
NXSSH_RCODE=0

case "$action" in
  "--install"        ) needSystem=1;;
  "--update"         ) needSystem=1;;
  "--uninstall"      ) needSystem=0;;
  "--preuninstall"   ) needSystem=0;;
  "--pre-uninstall"  ) needSystem=0;;
  "--usage"          ) needSystem=0;;
  "--help"           ) needSystem=0;;
  "--server-keygen"  ) needSystem=0;;
  "--keygen"         ) needSystem=0;;
  ""                 ) ARGS=-1 && printMsg "Please specify an action" "nolog" && needSystem=0 ;;
  *                  ) ARGS=-1 && printMsg "ERROR: Unknown action '$action'" "nolog" && needSystem=0 ;;
esac



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

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

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

if [ -f /etc/debian_version ];
then
  system=debian
  ISSUE=`head -c 6 /etc/issue 2>/dev/null`
  if [ "x$ISSUE" = "xUbuntu" ]
  then
    issue=ubuntu
  fi

fi

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

if [ "x$system" = "x" -a -f /etc/release ];
then
  system=solaris
  FILE_AUTHORIZED_KEYS="$NODE_ROOT/home/nx/.ssh/authorized_keys"
  NXSSH_RCODE=255
  if [ -f /etc/.login ];
  then
    rcCsh="/etc/.login"
  fi
fi

if [ -n "$2" ];
then
  ARGS=`expr $ARGS + 1`
  case "$2" in
    ""                ) ARGS=-1 && needSystem=0 ;;
    *                 ) system=$2 && needSystem=1;;
  esac
fi

if [ -n "$3" ];
then
  ARGS=`expr $ARGS + 1`
  system=$3 && needSystem=1;
fi

if [ "$needSystem" -eq 1 ];
then
  case "$system" in
    "redhat"             ) ;;
    "suse"               ) ;;
    "mandrake"           ) ;;
    "fedora"             ) ;;
    "debian"             ) ;;
    "solaris"             ) ;;
    ""                 ) 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 [ $# -ne "$ARGS" ]; # Check for proper no. of command line args.
then
  printusage
fi

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

procedureServerKeygen () {

  if [ -f $FILE_AUTHORIZED_KEYS ];
  then
    stopped="yes"
    stopNXServer
  fi
  printMsg "Starting: server-keygen operation at: $currentTime"
  if [ -f $NODE_ROOT/home/nx/.ssh/new.id_dsa ];
  then
    runShCommand "$RMCOMMAND -f '$NODE_ROOT/home/nx/.ssh/new.id_dsa'"
    if [ "x$LastCommand" != "x" ];
    then
      printMsg "Cannot delete not used ssh key" "error"
      printMsg "$LastCommand"
      if [ "x$stopped" = "xyes" ];
      then
        startNXServer
      fi
      exit 1
    fi
  fi

  if [ -f $NODE_ROOT/home/nx/.ssh/new.id_dsa.pub ];
  then
    runShCommand "$RMCOMMAND -f '$NODE_ROOT/home/nx/.ssh/new.id_dsa.pub'" 
    if [ "x$LastCommand" != "x" ];
    then
      printMsg "Cannot delete not used ssh key" "error"
      printMsg "$LastCommand"
      if [ "x$stopped" = "xyes" ];
      then
        startNXServer
      fi
      exit 1
    fi
  fi

  printMsg "Generating new ssh-keys. Please wait"
  runShCommand "ssh-keygen -q -t dsa -N '' -C '' -f '$NODE_ROOT/home/nx/.ssh/new.id_dsa'"

  if [ "x$LastCommand" != "x" ];
  then
    printMsg "Cannot generate SSH keys for NX Server authentication" "error"
    printMsg "$LastCommand"
    if [ "x$stopped" = "xyes" ];
    then
      startNXServer
    fi
    exit 1
  fi

   out=`/bin/bash -c "echo -n 'no-port-forwarding,no-agent-forwarding,command=\"$NXSHELL --login\" ' > $NODE_ROOT/home/nx/.ssh/tmp.id_dsa 2>&1"`

  if [ "$?" != "0" ];
  then
    printMsg "Cannot create SSH key for NX Server authentication" "error"
    printMsg "Error is: $out"
    if [ "x$stopped" = "xyes" ];
    then
      startNXServer
    fi
    if [ -f "$NODE_ROOT/home/nx/.ssh/tmp.id_dsa" ];
    then
      runShCommand "$RMCOMMAND -f $NODE_ROOT/home/nx/.ssh/tmp.id_dsa"
    fi
    exit 1
  fi

  runShCommand "cat $NODE_ROOT/home/nx/.ssh/new.id_dsa.pub >> $NODE_ROOT/home/nx/.ssh/tmp.id_dsa" 
  if [ "x$LastCommand" != "x" ];
  then
    printMsg "Cannot create SSH key for NX Server authentication" "error"
    printMsg "$LastCommand"
    if [ "x$stopped" = "xyes" ];
    then
      startNXServer
    fi
    runShCommand "$RMCOMMAND -f $NODE_ROOT/home/nx/.ssh/tmp.id_dsa"
    exit 1
  fi

  $RMCOMMAND -f "$NODE_ROOT/home/nx/.ssh/new.id_dsa.pub" 

  printMsg "Keys generated correctly. Backing up files"

  if [ -f "$NODE_ROOT/home/nx/.ssh/default.id_dsa.pub" ];
  then
    runShCommand "$MVCOMMAND -f '$NODE_ROOT/home/nx/.ssh/default.id_dsa.pub' '$NODE_ROOT/home/nx/.ssh/default.id_dsa.pub.backup'"
    if [ "x$LastCommand" != "x" ];
    then
      printMsg "Cannot create SSH key for NX Server authentication" "error"
      printMsg "$LastCommand"
      if [ "x$stopped" = "xyes" ];
      then
        startNXServer
      fi
      runShCommand "$RMCOMMAND -f $NODE_ROOT/home/nx/.ssh/tmp.id_dsa"
      exit 1
    fi
  fi

  if [ -f "$NODE_ROOT/share/keys/default.id_dsa.key" ];
  then
    runShCommand "$MVCOMMAND -f '$NODE_ROOT/share/keys/default.id_dsa.key' '$NODE_ROOT/share/keys/default.id_dsa.key.backup'" "Cannot backup ssh-keys"
  fi
  
  printMsg "Back up of keys made. Updating files"
  $MVCOMMAND -f "$NODE_ROOT/home/nx/.ssh/tmp.id_dsa" "$NODE_ROOT/home/nx/.ssh/default.id_dsa.pub" 
  $MVCOMMAND -f "$NODE_ROOT/home/nx/.ssh/new.id_dsa" "$NODE_ROOT/share/keys/default.id_dsa.key" 
  chmod 0644 "$NODE_ROOT/share/keys/default.id_dsa.key"
  printMsgNoDot "Keys updated. NX clients should now use key:"
  printMsgNoDot "$NODE_ROOT/share/keys/default.id_dsa.key"
  printMsg "to get connected to this NX server"
  if [ "x$stopped" = "xyes" ];
  then
    startNXServer
  fi
}

procedureInstallServer() {
  umask 022	
  if [ -f "$CONFIG_FILE" ];
  then
    procedureUpdateServer
    return 0
  else
  if [ -f "$CONFIG_FILE.backup" ];
    then
      $CPCOMMAND -f $CONFIG_FILE.backup $CONFIG_FILE 
    fi
  fi

  
  result=`id nx 2>&1`
  if [ $? = 0 ];
  then
#     printMsg "Cannot add user: nx. User: nx already exists" "error"
#     printMsg "Please try to fix the problem by reinstalling the server" "error"
    printMsg "Cannot add user: nx" "error"
    printMsg "User: nx already exists" "error"
    printMsgNoDot "To fix the problem, you may try to completely uninstall NX" 
    printMsgNoDot "Server and install it from scratch. If this is not enough,"
    printMsgNoDot "please delete the nx user by using the system commands and"
    printMsg "proceed with a new installation of NX Server"
    exit 1
  fi

  LOGFILE="$INSTALLOG"
  createLogdirectory
  startLog
  PROCESS="$INSTALL"
  printMsg "Installing: server at: $currentTime"
  printMsg "Autodetected system: $system"
  printMsg "Install log is: $LOGFILE"
#  printMsg "Installing $PRODUCT_NAME."

  if [ "$system" != "solaris" ];
  then
    addNXUserLinux
  else
    addNXUserSolaris
  fi
  setShell
  genNXUsersKeys
  makeNXConfigServer
  checkNXUsersFile
  checkNXConfiguration
#  validateLicenseFile
#  installLicenseFile
  upgradeLicenseFile
  validateNodeLicenseFile;
  addNXinit
  setNxStatisticDBPermissions
  startNXServer
  startNXStat
  selinuxOperations  
#  removeSystemConfig
#  removeNXSystemSetup
#  addNXSystemSetup
#  checkCupsConfig
#  SetCupsKey
#  nxPrintSetup
#  setNxuexecPermisions
  setNxsessregPermisions
#  setNXaddprinterPermissions
  setNxUserMngshPermissions

  checkSSHD

#  fixTempXDir

#  if [ "$system" = "redhat" ]; 
#  then
#    fixTempXDir__redhat
#  fi  

#  if [ "$system" = "mandrake" ]; 
#  then
#    fixTempXDir__redhat
#  fi

#  if [ "$system" = "fedora" ]; 
#  then
#    fixTempXDir__redhat
#  fi
  
#  if [ "$system" = "solaris" ];
#  then
#    fixTempXDir__solaris
#  fi

  if [ $SHOWWARNINFO = "yes" ];
  then
    printMsg "Installation of NX server was completed with warnings"
    printMsgNoDot "Please review the install log '$NODE_ROOT/var/log/install'"
    printMsg "for further details"
   else
    printMsg "Version '$VERSION' installation completed"
  fi


  if [ -f "$NODE_ROOT/share/documents/server/install-notices" ];
  then
    printMsgNoDot "Showing file: $NODE_ROOT/share/documents/server/install-notices" 
    cat $NODE_ROOT/share/documents/server/install-notices
  fi

  procedureprintbrandmessages
  
  echo ""
    
  printMsg "Bye"
  echo ""
  exit 0

}

procedureUninstallServer () {
  echo ""
  LOGFILE="$UNINSTALLOG"
  createLogdirectory
  startLog

  PROCESS="$UNINSTALL"
  printMsg "Uninstalling: server at: $currentTime"
  if [ -x $NXSHELL ];
  then
    printMsg "Shutting down"
    cmdout=`$NXSHELL --shutdown`
    if [ $? != 0 ];
    then
      printMsg "Cannot shutdown nxserver" "error"
      printMsg "$cmdout" "cmd"
      exit 1
    else 
      printMsg "Shutdown complete"
    fi
  fi

  printMsg "Autodetected system: $system"
  printMsg "Uninstall log is: $LOGFILE"
#  printMsg "Uninstalling $PRODUCT_NAME."

  if [ -f "$NODE_ROOT/etc/users.id_dsa" ];
  then
    printMsgNoDot "The NX setup program found that the NX server package was installed on the machine"
    printMsgNoDot "but the update procedure was never executed. To be able to successfully uninstall"
    printMsgNoDot "the NX server, you will need to run the 'nxsetup --update' procedure, first, and"
    printMsg "'nxserver --uninstall' afterward"
    exit 1
  fi

  removeNXNodesDB

  stopNXStat
  
  removeNXUser

#  removePrintSetup

#  removeSystemConfig

#  removeNXSystemSetup

  resetPermissionsServer
 
  archiveNXUsersKeys

#  resetPermissions

  resetNXConfigServer

  removeNXinit
  
  if [ $SHOWWARNINFO = "yes" ];
  then
    printMsg "Uninstall of NX server has been completed with warnings"
    printMsg "Please review the uninstall log for details"
  else
    printMsg "Uninstallation of version: $VERSION completed"
  fi

  if [ -f "$NODE_ROOT/share/documents/server/uninstall-notices" ];
  then
    printMsgNoDot "Showing file: $NODE_ROOT/share/documents/server/uninstall-notices"
    echo ""
    cat $NODE_ROOT/share/documents/server/uninstall-notices
  fi

  printMsg "Bye"
  echo ""
  exit 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"

    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] == "NXCLIENT") {
          tab[i] = "NXClient"
        } else if (tab[i] == "NXUEXEC") {
          tab[i] = "NXUexec"
        } 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

  sed -e 's|^ConfigFileVersion.*$|ConfigFileVersion = "2.0"|g' $CONFIG_FILE.tmp > $CONFIG_FILE

  runCommand "$RMCOMMAND $CONFIG_FILE.tmp" "Cannot remove '$CONFIG_FILE.tmp' file." "warn"
}

selinuxOperations() {
  if [ -x /usr/sbin/selinuxenabled ];
  then
    result=`/usr/sbin/selinuxenabled 2>&1`
    if [ $? = 0 ];
    then
      if [ -f "$FILE_AUTHORIZED_KEYS" ];
      then
        test -x /usr/bin/chcon && /usr/bin/chcon -t user_home_t $FILE_AUTHORIZED_KEYS
      fi
      test -x /usr/bin/chcon && /usr/bin/chcon -t shell_exec_t $NODE_ROOT/bin/nxserver
    fi
  fi
}

procedureUpdateServer() {
  umask 022
  if [ ! -f "$CONFIG_FILE" ];
  then
    printMsg "Initialization failed. Cannot open file: $CONFIG_FILE" "error"
    printMsgNoDot "No such file or directory. Please try to fix the problem by" "error"
    printMsg "running: $NODE_ROOT/scripts/setup/nxserver --install" "error"
    exit 1
  fi
  
  LOGFILE="$UPDATELOG"
  createLogdirectory
  startLog
  PROCESS="$UPDATE"
  printMsg "Updating: server at: $currentTime" 
  printMsg "Autodetected system: $system"
  printMsg "Update log is: $LOGFILE"
#  printMsg "Updating $PRODUCT_NAME."

  printMsg "Checking NX server configuration using $CONFIG_FILE file"

  grep "ConfigFileVersion" "$CONFIG_FILE" 1>/dev/null
  if [ "$?" != 0 ];
  then
    printMsg "Configuration file needs to be updated" "warn"
    printMsg "Copying original configuration to $CONFIG_FILE.backup" 
    $CPCOMMAND -f $CONFIG_FILE $CONFIG_FILE.backup
    printMsg "Creating new sample configuration file $NODE_ROOT/etc/server-$system.cfg.sample"
    printMsg "Updating $CONFIG_FILE file" 
    convertNXconfigToCamelCaseFormat
    SHOWUPDATEINFO="yes"
  fi

  fixoldnxhome
  fixoldpasswdfile
  fixoldusersfile
  fixoldkeyfile
  fixoldconffileServer
  #fixlicensefile
  checkNXUsersFile
  checkAdministratorsDb
  checkNXConfiguration
  checkNXkeys
  selinuxOperations
  upgradeLicenseFile
# checkCupsConfig

#  removeSystemConfig

#  if [ "$system" = "redhat" ]; 
#  then
#    fixTempXDir__redhat
#  fi
  
#  if [ "$system" = "mandrake" ];
#  then
#    fixTempXDir__redhat
#  fi

#  if [ "$system" = "fedora" ];
#  then
#    fixTempXDir__redhat
#  fi
  
#  if [ "$system" = "solaris" ];
#  then
#    fixTempXDir__solaris
#  fi

#  fixTempXDir
  
#  removeNXSystemSetup
#  addNXSystemSetup

#  if [ -f "$LICENSE_FILE" ];
#  then
#    runCommand "chown nx:root '$LICENSE_FILE'" "Cannot change ownership for '$LICENSE_FILE'" "error"
#    runCommand "chmod 0400 '$LICENSE_FILE'" "Cannot change permissions for '$LICENSE_FILE'" "error"
#  fi
  
  copySessionHistory
#  nxPrintSetup
  checkSessregPath
#  setNxuexecPermisions
  setNxsessregPermisions
#  setNXaddprinterPermissions
  setNxUserMngshPermissions
  setNxStatisticDBPermissions
  cleanShareDirectory

  if [ "$system" = "solaris" ];
  then
    enableNxUser
  fi

#  cleanRestrictedDirectory
#  removeNXinit
#  addNXinit
  startNXStat

  updateAutorizedKey

  checkStr=`$NXSHELL --upgradecheck 2>&1`
  result=`echo "$checkStr" | grep -c "expired" 2>&1`
  if [ "$result" != "0" ];
  then
    printMsgNoDot "Sorry, your upgrade period has expired. To be able to" "warn"
    printMsgNoDot "install a new version of the software, please visit the" "warn"
    printMsgNoDot "NoMachine Web site at http://www.nomachine.com/" "warn"
    printMsgNoDot "to acquire a valid subscription." "warn"
    exit 1
  fi

  checkSSHD "update"


  if [ $SHOWWARNINFO = "yes" ];
  then
    printMsgNoDot "Update of NX server has been completed with warnings"
    printMsg "Please review the update log for details"   
    #printMsg "update log ('$NODE_ROOT/var/log/update') for details"
  else  
    printMsg "Version '$VERSION' update completed"
  fi

  if [ -f "$NODE_ROOT/share/documents/server/update-notices" ];
  then
    if [ $SHOWUPDATEINFO = "yes" ];
    then
      printMsgNoDot "Showing file: $NODE_ROOT/share/documents/server/update-notices"
      cat $NODE_ROOT/share/documents/server/update-notices
    fi
  fi

#  if [ "$SHOWCUPSINFO" = "yes" ];
#    then
#      if [ -f "$NODE_ROOT/share/documents/server/cups-info" ];
#      then
#        cat $NODE_ROOT/share/documents/server/cups-info
#      fi
#  fi

  printMsg "Bye"
  echo ""

  exit 0
}

procedurePreuninstall () {
  LOGFILE="$UNINSTALLOG"
  createLogdirectory
  startLog
  PROCESS="$UNINSTALL"
  printMsg "Pre-uninstalling: server at: $currentTime"

  printMsg "Shutting down"

  cmdout=`$NXSHELL --shutdown`
  if [ $? != 0 ];
  then
    printMsg "Cannot shutdown nxserver" "error"
    printMsg "$cmdout" "cmd"
    exit 1
  else 
    printMsg "Shutdown complete"
  fi

  printMsg "Cleaning up NX session DB"
  stopNXStat
  cleanNXDb
  printMsg "Cleaned up NX session DB"
  printMsg "Bye"
  exit 0
}

procedureprintbrandmessages() {
  if [ -f "$NODE_ROOT/share/branding/server/branding.db" ];
  then
    licenceInfo=`head -n 1 "$NODE_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=`printf "$licenceInfo" | head -n $line | tail -n 1`
      if [ "x$txt" != "x" -a "x$prev" != "x$txt" ];
      then
        echo "$txt"
        prev=$txt
      else
        break
      fi
    done
  fi
  
#  echo
#  echo "Getting support"
#  echo

  if [ -f "$NODE_ROOT/share/branding/server/branding.db" ];
  then
    licenceInfo=`head -n 6 "$NODE_ROOT/share/branding/server/branding.db" 2>&1 | tail -n 1`
    prev=""
    for line in 1 2 3 4 5 6 7 8 9 10 ; do
      txt=""
      txt=`printf "$licenceInfo" | head -n $line | tail -n 1`
      if [ "x$txt" != "x" -a "x$prev" != "x$txt" ];
      then
        echo "$txt"
        prev=$txt
      else
        break
      fi
    done
  fi
}

if [ "$action" = "--install" ];
then
  procedureInstallServer
fi

if [ "$action" = "--uninstall" ];
then
  procedureUninstallServer
fi

if [ "$action" = "--update" ];
then
  procedureUpdateServer
fi

if [ "$action" = "--preuninstall" ] || [ "$action" = "--pre-uninstall" ];
then
  procedurePreuninstall
fi
  
if [ "$action" = "--server-keygen" ] || [ "$action" = "--keygen" ];
then
  LOGFILE="$UPDATELOG"
  createLogdirectory
  startLog
  procedureServerKeygen
fi

