#!/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-5"
PRODUCT_NAME="NX Node $VERSION"
CONFIG_VERSION="2.0"

NODE_ROOT="/usr/NX"
CONFIG_FILE="$NODE_ROOT/etc/node.cfg"
LICENSE_FILE="$NODE_ROOT/etc/node.lic"

WRAPPER="$NODE_ROOT/bin/nxuexec"

CUPS_PATH="/usr /opt/sfw/cups /usr/local /usr/lib /opt/csw"
SMB_PATH="/sbin /bin /usr/sbin /usr/bin /usr/local/sbin /usr/local/bin"

NXSPOOL="$NODE_ROOT/bin/nxspool"
NXPRINTERADDSH="$NODE_ROOT/scripts/restricted/nxprinteradd.sh"
NXPRINTERDELSH="$NODE_ROOT/scripts/restricted/nxprinterdel.sh"
NXINITSH="$NODE_ROOT/scripts/restricted/nxtmpperm.sh"
NXSETKEY="$NODE_ROOT/scripts/restricted/nxkeyadd.sh"
NXUSERADDSH="$NODE_ROOT/scripts/restricted/nxuseradd.sh"
NXUSERDELSH="$NODE_ROOT/scripts/restricted/nxuserdel.sh"
NXLICENSESH="$NODE_ROOT/scripts/restricted/nxlicense.sh"
NXSMBMOUNTSH="$NODE_ROOT/scripts/restricted/nxmountadd.sh"
NXSMBUMOUNTSH="$NODE_ROOT/scripts/restricted/nxmountdel.sh"

SSHDPort="22"

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

PREFIX="NX>"

NX_SETUP_VERSION="nxsetup 1.2.2"

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

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
  system=solaris
  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

# 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

}

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
}

removePrintSetup () {

CUPS_BACKEND=""
tmp=""

if [ ! -r "$CONFIG_FILE" ];
then
  return 1  
fi

tmp=`$AWKCOMMAND -F'"' '/^CUPSBackendPath/ {print $2}' $CONFIG_FILE`

if [ "x$tmp" != "x" ];
then
  if [ ! -h $tmp/nx ];
  then
    for tmp in $CUPS_PATH; do
      if test -h $tmp/cups/backend/nx ;
      then
        CUPS_BACKEND="$tmp/cups/backend";
        break;
      fi
    done
  else
    CUPS_BACKEND=$tmp
  fi
else
  for tmp in $CUPS_PATH; do
    if test -h $tmp/cups/backend/nx ;
    then
      CUPS_BACKEND="$tmp/cups/backend";
      break;
    fi
  done
fi

if [ "x$CUPS_BACKEND" != "x" ];
then
  if [ -h "$CUPS_BACKEND/nx" ];
  then
    runCommand "$RMCOMMAND -f $CUPS_BACKEND/nx" "Cannot remove nxdriver for cups in '$CUPS_BACKED' directory."

    if [ "$CUPS_BACKEND" = "/usr/lib64/cups/backend" ];
    then
      if [ -h "/usr/lib/cups/backend/nx" ];
      then
        runCommand "$RMCOMMAND -f  /usr/lib/cups/backend/nx" "Cannot remove nxdriver for cups in '/usr/lib/cups/backend' directory."
      fi
    fi

  fi
else
  printMsg "Cannot find cups/backend directory for remove nxdriver for cups"
fi

if [ -f "$NXPRINTERADDSH" ];
then
  runCommand "chmod 600 $NXPRINTERADDSH" "Cannot fix permissions of '$NXPRINTERADDSH' script" 
  runCommand "chown root:root $NXPRINTERADDSH" "Cannot fix ownership of '$NXPRINTERADDSH' script" 
fi

if [ -f "$NXPRINTERDELSH" ];
then
  runCommand "chmod 600 $NXPRINTERDELSH" "Cannot fix permissions of '$NXPRINTERDELSH' script" 
  runCommand "chown root:root $NXPRINTERDELSH" "Cannot fix ownership of '$NXPRINTERDELSH' script" 
fi
}

resetPermissions () {
#  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 "$NXUSERDELSH" ];
  then
    runCommand "chmod 744 $NXUSERDELSH" "Cannot fix permissions of '$NXUSERDELSH' script"
    runCommand "chown root:root $NXUSERDELSH" "Cannot fix ownership of '$NXUSERDELSH' script"
  fi

  if [ -f "$NXLICENSESH" ];
  then
    runCommand "chmod 744 $NXLICENSESH" "Cannot fix permissions of '$NXLICENSESH' script"
    runCommand "chown root:root $NXLICENSESH" "Cannot fix ownership of '$NXLICENSESH' script"
  fi

  if [ -f "$NXPRINTERADDSH" ];
  then
    runCommand "chmod 755 $NXPRINTERADDSH" "Cannot fix permissions of '$NXPRINTERADDSH' script"
    runCommand "chown root:root $NXPRINTERADDSH" "Cannot fix ownership of '$NXPRINTERADDSH' script"
  fi
  if [ -f "$NXPRINTERDELSH" ];
  then
    runCommand "chmod 755 $NXPRINTERDELSH" "Cannot fix permissions of '$NXPRINTERDELSH' script"
    runCommand "chown root:root $NXPRINTERDELSH" "Cannot fix ownership of '$NXPRINTERDELSH' script"
  fi
  if [ -f "$WRAPPER" ];
  then
    runCommand "chmod 755 $WRAPPER" "Cannot fix permissions of '$WRAPPER' script"
    runCommand "chown root:root $WRAPPER" "Cannot fix ownership of '$WRAPPER' script"
  fi
  if [ -f "$NXSETKEY" ];
  then
    runCommand "chmod 744 $NXSETKEY" "Cannot fix permissions of '$NXSETKEY' script"
    runCommand "chown root:root $NXSETKEY" "Cannot fix ownership of '$NXSETKEY' script"
  fi

  if [ -f "$NXINITSH" ];
  then
    runCommand "chmod 744 $NXINITSH" "Cannot fix permissions of '$NXINITSH' script"
    runCommand "chown root:root $NXINITSH" "Cannot fix ownership of '$NXINITSH' script"
  fi

  if [ -f "$NXUSERADDSH" ];
  then
    runCommand "chmod 744 $NXUSERADDSH" "Cannot fix permissions of '$NXUSERADDSH' script"
    runCommand "chown root:root $NXUSERADDSH" "Cannot fix ownership of '$NXUSERADDSH' script"
  fi

  if [ -f "$NXSMBMOUNTSH" ];
  then
    runCommand "chmod 744 $NXSMBMOUNTSH" "Cannot fix permissions of '$NXSMBMOUNTSH' script"
    runCommand "chown root:root $NXSMBMOUNTSH" "Cannot fix ownership of '$NXSMBMOUNTSH' script"
  fi

  if [ -f "$NXSMBUMOUNTSH" ];
  then
    runCommand "chmod 744 $NXSMBUMOUNTSH" "Cannot fix permissions of '$NXSMBUMOUNTSH' script"
    runCommand "chown root:root $NXSMBUMOUNTSH" "Cannot fix ownership of '$NXSMBUMOUNTSH' script"
  fi

  if [ -f "$NXUSERDELSH" ];
  then
    runCommand "chmod 744 $NXUSERDELSH" "Cannot fix permissions of '$NXUSERDELSH' script"
    runCommand "chown root:root $NXUSERDELSH" "Cannot fix ownership of '$NXUSERDELSH' script"
  fi
}

setDbusKeys () {

  if [ ! -r $CONFIG_FILE ];
  then
    return 1
  fi

  command="type dbus-launch"

  DBUS_PATH=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    return 1;
  fi

  command="which dbus-launch"

  DBUS_PATH=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    return 1;
  fi

  command="grep CommandStartGnome $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify path and name of the command to start the GNOME session.
#
CommandStartGnome=\"$DBUS_PATH --exit-with-session gnome-session\"
" >> $CONFIG_FILE;
  fi

  command="grep CommandStartKDE $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify path and name of the command to start the KDE session.
#
CommandStartKDE=\"$DBUS_PATH --exit-with-session startkde\"
" >> $CONFIG_FILE;
  fi

#printMsg "Inspecting local DBUS environment" 

#printMsg "Generating DBUS entries in: $CONFIG_FILE"

}

SetCupsKey () {

printMsg "Inspecting local CUPS environment" 
printMsg "Generating CUPS entries in: $CONFIG_FILE"

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

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

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

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

if [ "x$CUPS_BACKEND" != "x" -a "x$CUPS_BIN" != "x" -a "x$CUPS_SBIN" != "x" ];
then
  if [ -r "$CONFIG_FILE.tmp" ];
  then
    runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot delete temporary '$CONFIG_FILE.tmp' file" "warn"
  fi
  sed -e 's|^EnableCUPSSupport.*=.*$|EnableCUPSSupport = "1"|g' \
  -e 's|^CUPSBackendPath.*=.*$|CUPSBackendPath = "'$CUPS_BACKEND'"|g' \
  -e 's|^CUPSBinPath.*$|CUPSBinPath = "'$CUPS_BIN'"|g' \
  -e 's|^CUPSSbinPath.*$|CUPSSbinPath = "'$CUPS_SBIN'"|g' $CONFIG_FILE > $CONFIG_FILE.tmp

  if [ $? != 0 ];
  then
    printMsg "Problem with converting: $CONFIG_FILE file: $!"
    runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot delete temporary file: $CONFIG_FILE.tmp" "warn"
    return 1
  fi

  printMsg "Replacing: $CONFIG_FILE" "cmd"
  runCommand "$CPCOMMAND -f $CONFIG_FILE.tmp $CONFIG_FILE" "Cannot replace file: $CONFIG_FILE" "warn"
  printMsg "Deleting temporary file" "cmd"
  runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot remove file: $CONFIG_FILE.tmp" "warn"
else
  SHOWCUPSINFO="yes"
fi

}


nxPrintSetup () {

CUPS_BACKEND=""
tmp=""
tmp=`$AWKCOMMAND -F'"' '/^CUPSBackendPath/ {print $2}' $CONFIG_FILE 2>&1`
if [ $? != 0 ];
then
  printMsg "Cannot parse file $CONFIG_FILE: $tmp" "warn"
  return 1
fi

if [ "x$tmp" != "x" ];
then
  if [ -d $tmp ];
  then
    CUPS_BACKEND=$tmp
  fi
fi

if [ ! -x $NODE_ROOT/bin/nxspool ];
then
  printMsg "Cannot find file $NODE_ROOT/bin/nxspool" "warn"
  return 1
fi

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

if [ "x$CUPS_BACKEND" != "x" ];
then
  if [ -h "$CUPS_BACKEND/nx" ];
  then
    SHOWCUPSINFO="no"
  else 
    runCommand "ln -sf $NODE_ROOT/bin/nxspool $CUPS_BACKEND/nx" "Cannot install nx backend in '$CUPS_BACKEND' directory." "cmd"
    if [ "$CUPS_BACKEND" = "/usr/lib64/cups/backend" ];
    then
      if [ -d "/usr/lib/cups/backend" ];
      then
        if [ ! -h "/usr/lib/cups/backend/nx" ];
        then
          runCommand "ln -sf $NODE_ROOT/bin/nxspool /usr/lib/cups/backend/nx" "Cannot install nx backend in '/usr/lib/cups/backend' directory." "cmd"
        fi
      fi
    fi
  fi
else 
  SHOWCUPSINFO="yes"
fi

}

checkCupsConfig () {

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

    echo "# Enable or disable CUPS support:
#
# 1: Enabled. Enable CUPS support.
#
# 0: Disabled. Disable CUPS support.
#
EnableCUPSSupport = \"0\"

#
# Specify the path of directory holding the CUPS backend.
#
CUPSBackendPath=\"\"

#
# Specify the path of the directory holding CUPS binaries (f.e.
# the 'lpoptions' program).
#
CUPSBinPath=\"\"

#
# Specify the path of the directory holding CUPS programs and reserved
# for administrative purposes (f.e. 'cupsd' or 'lpadmin').
#
CUPSSbinPath=\"\"
" >> $CONFIG_FILE

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

setShareKey () {

  if [ ! -r $CONFIG_FILE ];
  then
    return 1
  fi

  HAVE_SMBFS="";
  HAVE_CIFS="";
#  HAVE_FUSE="";

  for tmp in $SMB_PATH; do
    if test -x $tmp/mount.smbfs ;
    then
      HAVE_SMBFS="X";
      break;
    fi
    if test -x $tmp/smbmount ;
    then
      HAVE_SMBFS="X";
      break;
    fi
  done

  for tmp in $SMB_PATH; do
    if test -x $tmp/mount.cifs ;
    then
      HAVE_CIFS="X";
      break;
    fi
  done

#  for tmp in $SMB_PATH; do
#    if [ -x $tmp/fusermount -a -f /usr/lib/libfuse.so ]
#    then
#      HAVE_FUSE="X";
#      break;
#    fi
#  done

  if [  "x$HAVE_SMBFS" = "xX"  -a  "x$HAVE_CIFS" = "xX" -a "x$HAVE_FUSE" = "xX" ];
  then
    MountShareProtocol="both";
    break;
  elif [ "x$HAVE_SMBFS" = "xX" ]
  then
    MountShareProtocol="smbfs";
    break;
  elif [ "x$HAVE_CIFS" = "xX" ]
  then
    MountShareProtocol="cifs";
    break;
#  elif [ "x$HAVE_FUSE" = "xX" ]
#  then
#    MountShareProtocol="fuse";
#    break;
  else
    MountShareProtocol="none";
    break;
  fi

  if [ -r "$CONFIG_FILE.tmp" ];
  then
    runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot delete temporary '$CONFIG_FILE.tmp' file" "warn"
  fi
  sed -e 's|^MountShareProtocol.*$|MountShareProtocol = "'$MountShareProtocol'"|g' $CONFIG_FILE > $CONFIG_FILE.tmp

  if [ $? != 0 ];
  then
    printMsg "Problem with converting: $CONFIG_FILE file: $!"
    runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot delete temporary file: $CONFIG_FILE.tmp" "warn"
    return 1
  fi

  printMsg "Replacing: $CONFIG_FILE" "cmd"
  runCommand "$CPCOMMAND -f $CONFIG_FILE.tmp $CONFIG_FILE" "Cannot replace file: $CONFIG_FILE" "warn"
  printMsg "Deleting temporary file" "cmd"
  runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot remove file: $CONFIG_FILE.tmp" "warn"

}

checkPrivilegesSmbScriptsKey () {
  if [ ! -r $CONFIG_FILE ];
  then
    return 1
  fi
  command="grep EnablePrivilegedSmbScripts $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
      echo "#
# Allow the server to use the privileged scripts to manage the SMB
#  shares.
# 
#  1: Enabled. When running the commands as the target user doesn't
#     work, the server will use the suid scripts to mount and unmount
#     the client shares.
# 
#  0: Disabled. Using the privileged scripts will not be allowed.
#     The mount will only be attempted by running the command as the
#     target user. If the host server is configured to forbid mounts by
#     unprivileged users, the operation will fail.
# 
#  By default, NX node will not use the privileged scripts so that the
#  system will behave according to the suid settings of the smbmount
#  and smbumount commands.
# 
#  Normally smbmount and smbumount can be set suid root to allow any
#  unprivileged user to mount his/her resources. By clearing the suid
#  bit and by letting the node use the privileged scripts, the system
#  administrator can gain greater control on the host node, by allowing
#  unprivileged users to mount their shares only within a NX session.  
#
#EnablePrivilegedSmbScripts = \"0\"
">> $CONFIG_FILE
  fi
}

fixTempXDir () {

  iceDir="/tmp/.ICE-unix"

  if [ ! -d "$iceDir" ];
  then
    runCommand "mkdir '$iceDir'" "Cannot create directory '$iceDir'" 
  fi

  runCommand "chown root:root '$iceDir'" "Cannot change ownership of '$iceDir' directory" "warn"

  runCommand "chmod 01777 '$iceDir'" "Cannot change permissions of '$iceDir' directory" "warn"

  x11Dir="/tmp/.X11-unix"

  if [ ! -d "$x11Dir" ];
  then
    runCommand "mkdir '$x11Dir'" "Cannot create '$x11Dir' directory" "warn"
  fi

  runCommand "chown root:root '$x11Dir'" "Cannot change ownership of '$x11Dir' directory" "warn"
  runCommand "chmod 01777 '$x11Dir'" "Cannot change permissions of '$x11Dir' directory" "warn"
}

selinuxOperations() {
  if [ -x /usr/sbin/selinuxenabled ];
  then
    result=`/usr/sbin/selinuxenabled 2>&1`
    if [ $? = 0 ];
    then
      if [ -x /sbin/restorecon ];
      then
        runCommand "/sbin/restorecon -v /tmp/.X11-unix" "Cannot restore security context for /tmp/.X11-unix directory" "warn"
      fi
    fi
  fi
}


setNxuexecPermisions () {

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

}

disableCupsSupport () {

if [ -r "$CONFIG_FILE.tmp" ];
  then
    runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot delete temporary '$CONFIG_FILE.tmp' file" "warn"
  fi

sed -e 's|^EnableCUPSSupport.*=.*$|EnableCUPSSupport = "0"|g' \
-e 's|^CUPSBackendPath.*=.*$|CUPSBackendPath = ""|g' \
-e 's|^CUPSBinPath.*$|CUPSBinPath = ""|g' \
-e 's|^CUPSSbinPath.*$|CUPSSbinPath = ""|g' $CONFIG_FILE > $CONFIG_FILE.tmp

if [ $? != 0 ];
then
  printMsg "Problem with converting file $CONFIG_FILE: $!"
  runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot delete temporary file $CONFIG_FILE.tmp" "warn"
  return 1
fi

printMsg "Replacing $CONFIG_FILE" "cmd"
runCommand "$CPCOMMAND -f $CONFIG_FILE.tmp $CONFIG_FILE" "Cannot replace file $CONFIG_FILE" "warn"
printMsg "Deleting temporary file" "cmd"
runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot remove file $CONFIG_FILE.tmp" "warn"

}

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


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


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

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

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

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


setNXaddprinterPermissions () {

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

  if [ ! -f "$NXPRINTERADDSH" ];
  then
    printMsg "Cannot find file $NXPRINTERADDSH" "warn"
    printMsg "Your package is incomplete"  "warn"
    printMsg "Disabling CUPS support" "warn"
    disableCupsSupport
    return 1
  fi

  if [ ! -f "$NXPRINTERDELSH" ];
  then
    printMsg "Cannot find file $NXPRINTERDELSH" "warn"
    printMsg "Your package is incomplete"  "warn"
    printMsg "Disabling CUPS support" "warn"
    disableCupsSupport
    return 1
  fi

  if [ "x$CUPS_BIN" = "x" ];
  then
    tmp=`$AWKCOMMAND -F'"' '/^CUPSBinPath/ {print $2}' $CONFIG_FILE 2>& 1`
    if [ $? != 0 ];
    then
      printMsg "Cannot parse file $CONFIG_FILE: $tmp" "warn"
      return 1
    elif [ "x$tmp" != "x" ];
      then
        CUPS_BIN=$tmp
      else
        printMsg "CUPS not configured correctly" "warn"
        printMsg "Check key 'CUPSBinPath' in 'file $CONFIG_FILE" "warn"
        return 1
    fi
  fi

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

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

  sysgroup=`grep "SystemGroup" $cupsdconf|awk '{print $1}'`;
  if [ "x$sysgroup" = "xSystemGroup" ];
  then
    for i in `grep "SystemGroup" $cupsdconf`;
    do
      if [ "x$i" != "xSystemGroup" ]  && [ "x$i" != "xroot" ];
      then
        cupsgroup="$i"
        break;
      fi
    done;
  else
    cupsgroup=`/bin/ls -l $printersconf | $AWKCOMMAND -F' '  '{print $4}' 2>& 1`
    if [ "$?" != 0 ];
    then
      printMsg "Cannot check group id of file $printersconf: $cupsgroup" "log"
      return 1
    elif [ "x$cupsgroup" = "x" ];
    then
      printMsg "Cannot find group id of printers.conf" "log"
      return 1
    fi
    cupsgroup=`echo $cupsgroup`
  fi
 
  script="$NXPRINTERADDSH"
  if [ -f "$script" ];
    then 
      runCommand "chown root:$cupsgroup '$script'" "Cannot change ownership of '$script' to 'nx:$cupsgroup'"
      runCommand "chmod 555 '$script'" "Cannot set permissions attributes for '$script' to '555'"
      runCommand "chmod g+s '$script'" "Cannot set permissions attributes for '$script' to 'g+s'" 
    else
      printMsg "No such file: $script" "warn"
  fi
  script="$NXPRINTERDELSH"
  if [ -f "$script" ];
    then 
      runCommand "chown root:$cupsgroup '$script'" "Cannot change ownership of '$script' to 'nx:$cupsgroup'"
      runCommand "chmod 555 '$script'" "Cannot set permissions attributes for '$script' to '555'"
      runCommand "chmod g+s '$script'" "Cannot set permissions attributes for '$script' to 'g+s'" 
    else
      printMsg "No such file: $script" "warn"
  fi

}

setNxPasswdPermissions () {

  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
}

setNxLicensePermissions () {

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

fixTempXDir__solaris () {

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

}

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/nxsensor" "Unable to remove '/etc/init.d/nxsensor'" "warn"

  if [ "$system" = "solaris" ];
  then
      if [ -h /etc/rc0.d/K99nxsensor ];
      then
        runCommand "$RMCOMMAND -r /etc/rc0.d/K99nxsensor" "Unable to remove '/etc/rc0.d/K99nxsensor'" "warn"
      fi
      if [ -h /etc/rc2.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -r /etc/rc2.d/S99nxsensor" "Unable to remove '/etc/rc2.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc3.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -r /etc/rc3.d/S99nxsensor" "Unable to remove '/etc/rc3.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc0.d/K01nxsensor ];
      then
        runCommand "$RMCOMMAND -r /etc/rc0.d/K01nxsensor" "Unable to remove '/etc/rc0.d/K01nxsensor'" "warn"
      fi
      if [ -h /etc/rc6.d/K01nxsensor ];
      then
        runCommand "$RMCOMMAND -r /etc/rc6.d/K01nxsensor" "Unable to remove '/etc/rc6.d/K01nxsensor'" "warn"
      fi
      if [ -h /etc/rc5.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -r /etc/rc5.d/S99nxsensor" "Unable to remove '/etc/rc5.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc6.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -r /etc/rc6.d/S99nxsensor" "Unable to remove '/etc/rc6.d/S99nxsensor'" "warn"
      fi
  elif [ "$system" = "suse" ];
    then
      if [ -h /etc/init.d/rc3.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/init.d/rc3.d/S99nxsensor" "Unable to remove '/etc/init.d/rc3.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/init.d/rc2.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/init.d/rc2.d/S99nxsensor" "Unable to remove '/etc/init.d/rc2.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/init.d/rc5.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/init.d/rc5.d/S99nxsensor" "Unable to remove '/etc/init.d/rc5.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/init.d/rc6.d/S99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/init.d/rc6.d/S99nxsensor" "Unable to remove '/etc/init.d/rc6.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/init.d/rc6.d/K99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/init.d/rc6.d/K99nxsensor" "Unable to remove '/etc/init.d/rc6.d/K99nxsensor'" "warn"
      fi
      if [ -h /etc/init.d/rc6.d/K01nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/init.d/rc6.d/K01nxsensor" "Unable to remove '/etc/init.d/rc6.d/K01nxsensor'" "warn"
      fi
      if [ -h /etc/init.d/rc0.d/K99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/init.d/rc0.d/K99nxsensor" "Unable to remove '/etc/init.d/rc0.d/K99nxsensor'" "warn"
      fi
      if [ -h /etc/init.d/rc0.d/K01nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/init.d/rc0.d/K01nxsensor" "Unable to remove '/etc/init.d/rc0.d/K01nxsensor'" "warn"
      fi

  elif [ "$system" = "debian" ];
    then
      if [ -h /etc/rc3.d/S99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc3.d/S99nxsensor" "Unable to remove '/etc/rc3.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc2.d/S99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc2.d/S99nxsensor" "Unable to remove '/etc/rc2.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc5.d/S99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc5.d/S99nxsensor" "Unable to remove '/etc/rc5.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc6.d/K99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc6.d/K99nxsensor" "Unable to remove '/etc/rc6.d/K99nxsensor'" "warn"
      fi
      if [ -h /etc/rc6.d/K01nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc6.d/K01nxsensor" "Unable to remove '/etc/rc6.d/K01nxsensor'" "warn"
      fi
      if [ -h /etc/rc6.d/S99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc6.d/S99nxsensor" "Unable to remove '/etc/rc6.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc0.d/K99nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc0.d/K99nxsensor" "Unable to remove '/etc/rc0.d/K99nxsensor'" "warn"
      fi
      if [ -h /etc/rc0.d/K01nxsensor ];
      then
      runCommand "$RMCOMMAND -f /etc/rc0.d/K01nxsensor" "Unable to remove '/etc/rc0.d/K01nxsensor'" "warn"
      fi

  else
      if [ -h /etc/rc.d/rc3.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc3.d/S99nxsensor" "Unable to remove '/etc/rc.d/rc3.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc2.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc2.d/S99nxsensor" "Unable to remove '/etc/rc.d/rc2.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc5.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc5.d/S99nxsensor" "Unable to remove '/etc/rc.d/rc5.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc6.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc6.d/S99nxsensor" "Unable to remove '/etc/rc.d/rc6.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc6.d/K99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc6.d/K99nxsensor" "Unable to remove '/etc/rc.d/rc6.d/K99nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc6.d/K01nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc6.d/K01nxsensor" "Unable to remove '/etc/rc.d/rc6.d/K01nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc0.d/S99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc0.d/S99nxsensor" "Unable to remove '/etc/rc.d/rc0.d/S99nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc0.d/K99nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc0.d/K99nxsensor" "Unable to remove '/etc/rc.d/rc0.d/K99nxsensor'" "warn"
      fi
      if [ -h /etc/rc.d/rc0.d/K01nxsensor ];
      then
        runCommand "$RMCOMMAND -f /etc/rc.d/rc0.d/K01nxsensor" "Unable to remove '/etc/rc.d/rc0.d/K01nxsensor'" "warn"
      fi

  fi
}


addNXinit () {

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

 temppdir=`pwd`

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


checkNXConfiguration () {
  if [ ! -f "$CONFIG_FILE" ];
  then
    printMsg "Creating configuration in '$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 [ "$system" = "ubuntu" ];
      then
        syscfg="debian";
      else
        syscfg=$system;
      fi
      if [ -f "$NODE_ROOT/etc/node-$syscfg.cfg.sample" ];
      then
        runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/node-$system.cfg.sample' '$CONFIG_FILE'" "Cannot copy '$NODE_ROOT/etc/node-$system.cfg.sample' to '$CONFIG_FILE'" "error"
      else
        printMsg "Cannot create configuration file" "error"
        exit 1
      fi
    fi
  fi

}

setEtcDirPermissions () {
  result=`id nx 2>&1`
  if [ $? = 0 ];
  then
    runCommand "chown nx:root '$NODE_ROOT/etc'" "Cannot set ownership attributes for '$NODE_ROOT/etc' to 'nx:root'" "warn"
  fi
}

checkNXconfig () {

  printMsg "Checking NX node configuration using $CONFIG_FILE file"

  grep "ConfigFileVersion" "$CONFIG_FILE" 1>/dev/null
  if [ "$?" != 0 ];
  then
    SHOWUPDATEINFO="yes"
    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/node-$system.cfg.sample" 
    printMsg "Updating $CONFIG_FILE file" 
    convertNXconfigToCamelCaseFormat
  else
    grep "ConfigFileVersion" "$CONFIG_FILE" | grep "$CONFIG_VERSION" 1>/dev/null
    if [ "$?" != 0 ];
    then
      SHOWUPDATEINFO="yes"
      printMsg "Configuration file in $VERSION has changed" "warn"
      printMsg "Creating new sample configuration file $NODE_ROOT/etc/node-$system.cfg.sample" 
    fi
  fi
}

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

    while (length(tab[i])) {
      if(!(tab[i] in keyUpper)) {
        if (tab[i] == "XKBCOMP") {
          tab[i] = "XkbComp"
        } else if (tab[i] == "XDPYINFO") {
          tab[i] = "XdpyInfo"
        } else if (tab[i] == "NXDIALOG") {
          tab[i] = "NXDialog"
        } else if (tab[i] == "NXNODE") {
          tab[i] = "NXNode"
        } else if (tab[i] == "NXAGENT") {
          tab[i] = "NXAgent"
        } else if (tab[i] == "NXPROXY") {
          tab[i] = "NXProxy"
        } else if (tab[i] == "NXDESKTOP") {
          tab[i] = "NXDesktop"
        } else if (tab[i] == "NXCLIENT") {
          tab[i] = "NXClient"
        } else if (tab[i] == "NXVIEWER") {
          tab[i] = "NXViewer"
        } else if (tab[i] == "NXPASSWD") {
          tab[i] = "NXPasswd"
        } else if (tab[i] == "NXUEXEC") {
          tab[i] = "NXUexec"
        } else if (tab[i] == "NXSENSOR") {
          tab[i] = "NXSensor"
        } else if (tab[i] == "MKDIR") {
          tab[i] = "MkDir"
        } else if (tab[i] == "LPOPTIONS") {
          tab[i] = "LpOptions"
        } else if (tab[i] == "SETXKBMAP") {
          tab[i] = "SetXkbMap"
        } else if (tab[i] == "PFILES") {
          tab[i] = "PFiles"
        } else {
          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"

}

makeNXConfig () {

  if [ -f "$CONFIG_FILE" ];
  then
    checkNXconfig
  else
    printMsg "Creating configuration in $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 [ "$system" = "ubuntu" ];
      then
        syscfg="debian";
      else
        syscfg=$system;
      fi
      if [ -f "$NODE_ROOT/etc/node-$syscfg.cfg.sample" ];
      then
        runCommand "$CPCOMMAND -f '$NODE_ROOT/etc/node-$system.cfg.sample' '$CONFIG_FILE'" "Cannot copy '$NODE_ROOT/etc/node-$system.cfg.sample' to '$CONFIG_FILE'" "error"
      else
        printMsg "Cannot create configuration file" "error"
        exit 1
      fi
    fi
  fi
  #runCommand "chown root:root '$NODE_ROOT/etc'" "Cannot set ownership attributes for '$NODE_ROOT/etc' to 'nx:root'" "error"

}

resetNXConfig () {

  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

  runCommand "chown -R root:root '$NODE_ROOT'" "Cannot change ownership of $NODE_ROOT directory" "warn"
}

fixStatisticsHost() {

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

upgradeConfigFile () {

  fixStatisticsHost

  command="grep SSHDCheckIP $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Accept or refuse the NX server connection if SSHD does not export
# the 'SSH_CONNECTION' and 'SSH_CLIENT' variables in the
# environment passed to the NX node.
#
# 1: Refuse. Check the remote IP and don't accept the connection
#    if it can't be determined.
#
# 0: Accept. Check the remote IP and accept the connection even if
#    the remote IP is not provided.
#
#SSHDCheckIP = \"0\"
" >> $CONFIG_FILE
  fi

  command="grep UserNXDirectoryPath $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify a different path from the default, i.e. user's home, where
# the .nx directory has to be created to store session files. If it
# doesn't exist yet, NX node will try to create a sub-directory for
# each of the users starting a session there, named as username, and
# will create the .nx under that sub-directory. For example, if this
# key is set to /tmp/nxdir/, when user nxtest runs the first session,
# the node will try to create the /tmp/nxdir/nxtest/.nx directory.
# The directory specifed in the UserNXDirectoryPath key needs to
# have proper ownership and permissions set to ensure that the node,
# running as the user, can access it. I.e. the directory should be
# writeable for all users or alternatively, the administrator should
# create a directory, with proper ownership and permissions, named as
# username, for each of the users who need to start sessions there.
# 
#UserNXDirectoryPath = \"\"
"  >> $CONFIG_FILE
  fi


  command="grep ClipboardBufferLimit $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Set the maximum amount of data that can be copied from within the
# NX session to the client. The default value is unlimited. Limit for
# the size of the buffer on copy operations has to be specified in
# bytes.
#
#ClipboardBufferLimit = \"unlimited\"
"  >> $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
# and session type as its input.
#
# E.g. UserScriptBeforeSessionStart = \"/tmp/nxscript/script.sh\"
#
#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 and
# session type as its input.
#
#UserScriptAfterSessionStart = \"\"
"  >> $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 and
# username 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 and username
# as its input.
#
#UserScriptAfterSessionSuspend = \"\"
"  >> $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 and username 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 and username 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 and
# username 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 and user-
# name as its input.
#
#UserScriptAfterSessionReconnect = \"\"
"  >> $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 and
# session type as its input.
#
#UserScriptAfterSessionFailure = \"\"
"  >> $CONFIG_FILE
  fi

  command="grep CommandXdpyInfo $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify path and name of the command 'xdpyinfo' for displaying
# information about an X server.
#" >> $CONFIG_FILE
  if [ "$system" = "solaris" ];
  then
    echo "CommandXdpyInfo = \"/usr/openwin/bin/xdpyinfo\"
"  >> $CONFIG_FILE
  else
    echo "CommandXdpyInfo = \"xdpyinfo\"i
"  >> $CONFIG_FILE
  fi

  fi

  command="grep EnableSensor  $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable running nxsensor:
#
# 1: Enabled.
#
# 0: Disabled.
#
# Run the nxsensor daemon in the background. This daemon can be used
# to produce statistics about the node machine. Produced data is to
# be queried and elaborated by the nxstat daemon running on the NX
# server host machine.
#
#EnableSensor = \"0\" 
" >> $CONFIG_FILE
  fi

  command="grep StatisticsHost $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify the hostname or IP address where the nxstat daemon, in
# charge of collecting and elaborating data provided by nxsensor,
# will be assumed to run. 
#
#StatisticsHost = \"127.0.0.1\"
"  >> $CONFIG_FILE
  fi

  command="grep EnablePulldownMenu $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Enable or disable the pulldown dialog, which provides a graphical
# way to suspend or terminate the rootless session:
#
# 1: Enabled. The pulldown menu is shown when the mouse pointer
#    moves near the middle of the top boundary of a window and
#    allows the user to suspend or terminate the session by means
#    of an icon-click.
#
# 0: Disabled. The ctrl+alt+T key combination has to be issued
#    to get the dialog for suspending or terminating the session.
#
#EnablePulldownMenu = \"1\"
"  >> $CONFIG_FILE
  fi


  command="grep CommandClient $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify path and name of the client to be run by nxnode, nxcomp
# and nxagent, for example for issuing dialog boxes and messages,
# instead of the default nxclient.
#
#CommandClient = \"/usr/NX/bin/nxclient\"
"  >> $CONFIG_FILE
  fi

# Removing AgentExtraOptionsRFB and AgentExtraOptionsRDP keys.
sed -e '
/#$/{
N
/# Append arguments to the command line used to run the NX agent for*$/{
N
/# RFB (VNC sessions).*$/{
  N
  N
  N
  N
  N
  N
  N
  d
  }
}
}' $CONFIG_FILE | sed -e '/#$/{
N
/# Append arguments to the command line used to run the NX agent for*$/{
N
/# RDP (Windows sessions).*$/{
  N
  N
  N
  N
  N
  N
  N
  d
  }
}
}' > $CONFIG_FILE.tmp

runCommand "$MVCOMMAND '$CONFIG_FILE.tmp' '$CONFIG_FILE'" "Cannot move '$CONFIG_FILE.tmp' file to '$CONFIG_FILE'" "error"


 command="grep CommandStartRDP $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify path and name of the command to start the RDP Client.
#
CommandStartRDP=\"rdesktop -f\"
" >> $CONFIG_FILE;
  fi

  command="grep CommandStartRFB $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    echo "#
# Specify path and name of the command to start the RFB Client.
#
CommandStartRFB=\"vncviewer -fullscreen\"
" >> $CONFIG_FILE;
  fi

}


fixoldconffile () {

  if [ -f "$NODE_ROOT/etc/node.conf" ];
  then
    runCommand "$MVCOMMAND '$NODE_ROOT/etc/node.conf' '$CONFIG_FILE'" "Cannot move '$NODE_ROOT/etc/node.conf' file to '$CONFIG_FILE'" "error"
  fi

  command="grep AgentExtraOptionsX $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? = 0 ];
  then
      sed -e 's|AgentExtraOptionsX|AgentExtraOptions|g' $CONFIG_FILE > $CONFIG_FILE.tmp && cp -f $CONFIG_FILE.tmp $CONFIG_FILE && $RMCOMMAND -f $CONFIG_FILE.tmp
  fi

  command="grep DefaultRDPDomain $CONFIG_FILE"  
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? != 0 ];
  then
    command="grep RDP_DOMAIN $CONFIG_FILE"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ $? = 0 ];
    then
      sed -e 's|RDP_DOMAIN|DefaultRDPDomain|g' $CONFIG_FILE > $CONFIG_FILE.tmp && cp -f $CONFIG_FILE.tmp $CONFIG_FILE && $RMCOMMAND -f $CONFIG_FILE.tmp
    else
      echo "#
# Specify the domain of the Windows Terminal Server.
#
#DefaultRDPDomain = \"\"
" >> $CONFIG_FILE
    fi
  fi

  command="grep CUPS_SUPPORT $CONFIG_FILE"
  outCommand=`/bin/bash -c "$command" 2>&1`
  if [ $? = 0 ];
  then
    command="grep EnableCUPSSupport $CONFIG_FILE"
    outCommand=`/bin/bash -c "$command" 2>&1`
    if [ $? != 0 ];
    then
      sed -e 's|CUPS_SUPPORT|EnableCUPSSupport|g' \
      -e 's|CUPS_BACKEND|CUPSBackendPath|g' \
      -e 's|CUPS_BIN|CUPSBinPath|g' \
      -e 's|CUPS_SBIN|CUPSSbinPath|g' $CONFIG_FILE > $CONFIG_FILE.tmp
      if [ $? != 0 ];
      then
        printMsg "Problem with converting '$CONFIG_FILE' file: $!"
        runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot delete temporary '$CONFIG_FILE.tmp' file" "warn"
        return 1
      else
        printMsg "Replacing $CONFIG_FILE" "cmd"
        runCommand "$CPCOMMAND -f $CONFIG_FILE.tmp $CONFIG_FILE" "Cannot replace '$CONFIG_FILE' file" "warn"
        printMsg "Deleting temporary file" "cmd"
        runCommand "$RMCOMMAND -f $CONFIG_FILE.tmp" "Cannot remove '$CONFIG_FILE.tmp' file" "warn"
      fi
      SetCupsKey
    fi
  fi
}

cleanRestrictedDirectory () {

  if [ -d "$NODE_ROOT/restricted" ];
  then
    if [ -f "$NXPRINTERADDSH" ];
    then
      runCommand "$RMCOMMAND -f $NXPRINTERADDSH" "Cannot remove $NXPRINTERADDSH" "cmd"
    fi

    if [ -f "$NXPRINTERDELSH" ];
    then
      runCommand "$RMCOMMAND -f $NXPRINTERDELSH" "Cannot remove $NXPRINTERDELSH" "cmd"
    fi

    if [ -f "$NXPASSWDSH" ];
    then
      runCommand "$RMCOMMAND -f $NXPASSWDSH" "Cannot remove $NXPASSWDSH" "cmd"
    fi
 
    if [ -f "$NXSETKEY" ];
    then
      runCommand "$RMCOMMAND -f $NXSETKEY" "Cannot remove $NXSETKEY" "cmd"
    fi

    if [ -f "$NXINITSH" ];
    then
      runCommand "$RMCOMMAND -f $NXINITSH" "Cannot remove $NXINITSH" "cmd"
    fi

    if [ -f "$NXUSERADDSH" ];
    then
      runCommand "$RMCOMMAND -f $NXUSERADDSH" "Cannot remove $NXUSERADDSH" "cmd"
    fi

    if [ -f "$NXUSERDELSH" ];
    then
      runCommand "$RMCOMMAND -f $NXUSERDELSH" "Cannot remove $NXUSERDELSH" "cmd"
    fi

    if [ -f "$NXLICENSESH" ];
    then
      runCommand "$RMCOMMAND -f $NXLICENSESH" "Cannot remove $NXLICENSESH" "cmd"
    fi
     
    if [ -f "$NXINITSH" ];
    then
      runCommand "$RMCOMMAND -f $NXINITSH" "Cannot remove $NXINITSH" "cmd"
    fi
    runCommand "rmdir $NODE_ROOT/restricted" "Cannot remove directory $NODE_ROOT/restricted" "cmd"
  fi
}

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

upgradeLicenseFile () {

  if [ -f "$LICENSE_FILE" ];
  then
    removeLicenseSampleFile
    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
    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 root: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 "$NODE_ROOT/bin/nxnode --validate" "Cannot validate license file"
  fi
}

removeLicenseSampleFile () {

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

}


printusage () {
  
  echo
  echo "Usage: `basename $0` ACTION"
  echo
  echo "Actions:"
  echo
  #echo "--check             Performs some system tests that checks the"
  #echo "                    minimal requirements for the installation."

  echo "--install        {SYSTEM}   Run the NX node install procedure for the"
  echo "                            specified system or distribuition"
  echo 
  echo "--update         {SYSTEM}   Run the NX node update procedure for the"
  echo "                            specified system or distribution"
  echo 
  echo "--uninstall                 Run the NX node uninstall procedure for the"
  echo "                            specified system or distribution"
  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
NXSSH_RCODE=0

case "$action" in
  "--install"        ) needSystem=1;;
  "--update"         ) needSystem=1;;
  "--uninstall"      ) needSystem=0;;
  "--usage"          ) needSystem=0;;
  "--help"           ) needSystem=0;;
  "--nxprintsetup"   ) 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
  NXSSH_RCODE=255
  if [ -f /etc/.login ];
  then
    rcCsh="/etc/.login"
  fi

fi

if [ -n "$2" ];
then
  ARGS=`expr $ARGS + 1`
  if [ "$action" = "--nxprintsetup" ];
  then
    CUPS_PATH="$CUPS_PATH $2"
  else
    case "$2" in
      ""                ) ARGS=-1 && needSystem=0 ;;
      *                 ) system=$2 && needSystem=1;;
    esac
  fi
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

procedureInstall () {

  umask 022
  if [ -f "$CONFIG_FILE" ];
  then
    procedureUpdate
    return 0
  else
  if [ -f "$CONFIG_FILE.backup" ];
    then
      $CPCOMMAND -f $CONFIG_FILE.backup $CONFIG_FILE 
    fi
  fi

  LOGFILE="$INSTALLOG"
  createLogdirectory
  startLog
  PROCESS="$INSTALL"
  printMsg "Starting: install $PACKAGE operation at: $currentTime"
  printMsg "Autodetected system '$system'"
  printMsg "Install log is '$LOGFILE'"

  #checkNXConfiguration
  makeNXConfig

  addNXinit

  removeSystemConfig

  removeNXSystemSetup
  checkCupsConfig
  SetCupsKey
  nxPrintSetup
  setDbusKeys
  setShareKey
  setNxuexecPermisions
  setNxKeyAddPermissions
  setNxInitShPermissions
  setNXaddprinterPermissions
  setNxUseraddshPermissions
  upgradeLicenseFile
  setNxLicensePermissions

  setEtcDirPermissions

  fixTempXDir
  selinuxOperations
  if [ "$system" != "solaris" ];
  then 
    setNxSmbMountPermissions
    setNxSmbUMountPermissions
  fi

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

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

  if [ -f "$NODE_ROOT/share/documents/node/install-notices" ];
  then
    #echo "NX> 700"
    printMsgNoDot "Showing file: $NODE_ROOT/share/documents/node/install-notices" 
    cat $NODE_ROOT/share/documents/node/install-notices
  fi

  if [ "$SHOWCUPSINFO" = "yes" ];
  then
    if [ -f "$NODE_ROOT/share/documents/node/cups-info" ];
    then
      printMsgNoDot "Showing file: $NODE_ROOT/share/documents/node/cups-info"
      cat $NODE_ROOT/share/documents/node/cups-info
    fi
  fi

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

  printMsg "Bye"
  echo ""
  exit 0

}


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

  PROCESS="$UNINSTALL"
  printMsg "Starting: uninstall operation at: $currentTime"
  printMsg "Autodetected system '$system'"
  printMsg "Uninstall log is '$LOGFILE'"
#  printMsg "Uninstalling $PRODUCT_NAME."

  removePrintSetup

  removeSystemConfig

  removeNXSystemSetup

  resetPermissions

  removeNXinit

  resetNXConfig
  cleanRestrictedDirectory

  if [ $SHOWWARNINFO = "yes" ];
  then
    printMsg "Uninstall of NX node has been completed with warnings: please review the"
    printMsg "uninstall log ('$NODE_ROOT/var/log/uninstall') for details"
  else
    printMsg "Version '$VERSION' uninstall completed"
  fi

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

  printMsg "Bye"
  echo ""
  exit 0
}

procedureUpdate () {

  umask 022
  if [ ! -f "$CONFIG_FILE" ];
  then
    printMsgNoDot "Initialization failed. Cannot open file: $CONFIG_FILE" "error"
    printMsgNoDot "No such file or directory. Please try to fix the problem by" "error"
    printMsgNoDot "running: $NODE_ROOT/scripts/setup/nxnode --install." "error"
    exit 1
  fi

  LOGFILE="$UPDATELOG"
  createLogdirectory
  startLog
  PROCESS="$UPDATE"
  printMsg "Autodetected system '$system'"
  printMsg "Update log is '$LOGFILE'"
  printMsg "Updating node at: $currentTime"
  checkNXconfig
  fixoldconffile
  checkNXConfiguration


  checkCupsConfig
  setDbusKeys

  upgradeLicenseFile

  removeSystemConfig

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

  if [ "$system" != "solaris" ];
  then
    setNxSmbMountPermissions
    setNxSmbUMountPermissions
    checkPrivilegesSmbScriptsKey
  fi

  fixTempXDir
  selinuxOperations
  removeNXSystemSetup
#  addNXSystemSetup
	
  nxPrintSetup
  setNxuexecPermisions
  setNxKeyAddPermissions
  setNxInitShPermissions
  setNXaddprinterPermissions
  setNxUseraddshPermissions
  setNxLicensePermissions
  upgradeConfigFile
  setEtcDirPermissions 

  cleanShareDirectory

  checkStr=`$NODE_ROOT/bin/nxnode --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 "o acquire a valid subscription." "warn"
    exit 1
  fi


  if [ $SHOWWARNINFO = "yes" ];
  then
    printMsg "Update of NX node has been completed with warnings"
    printMsg "Please review the update log for details"
  else  
    printMsg "Update of version: $VERSION completed"
  fi

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

  if [ "$SHOWCUPSINFO" = "yes" ];
    then
      if [ -f "$NODE_ROOT/share/documents/node/cups-info" ];
      then
        printMsgNoDot "Showing file: $NODE_ROOT/share/documents/node/cups-info"
        cat $NODE_ROOT/share/documents/node/cups-info
      fi
  fi

  printMsg "Bye"
  echo ""

  exit 0
}

procedureNxprintsetup() {

    LOGFILE="$UPDATELOG"
    createLogdirectory
    startLog
    PROCESS="$UPDATE"
    if [ ! -r "$CONFIG_FILE" ];
    then
      printMsg "ERROR: Cannot open: $CONFIG_FILE" "err"
      exit 1
    fi
    printMsg "Starting: nxprintsetup operation at: $currentTime"
    checkCupsConfig    
    SetCupsKey
    nxPrintSetup
    setNXaddprinterPermissions
    if [ "$SHOWCUPSINFO" = "yes" ];
    then
      cat $NODE_ROOT/share/documents/server/cups-info
    else
      printMsg "CUPS configuration updated"
    fi
}

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

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

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

if [ "$action" = "--preuninstall" ] || [ "$action" = "--pre-uninstall" ];
then
  procedurePreuninstall
fi
  
if [ "$action" = "--nxprintsetup" ];
then
  procedureNxprintsetup
fi

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

