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

# Basic support for RedHat style chkconfig
#
# chkconfig: - 99 01
# description: Starts and stops the NoMachine NX Server.
#
### BEGIN INIT INFO
# Provides:       nxserver
# Required-Start: $local_fs $remote_fs
# Should-Start: $network sshd
# Required-Stop:  $local_fs $remote_fs
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Description:    Starts and stops the NoMachine NX Server.
### END INIT INFO

ETC_DIR='/etc/NX'
USR_DIR='NX_ROOT'

[ -f $ETC_DIR/nxserver ] || { echo "ERROR: $ETC_DIR/nxserver doesn't exist" ; exit 1; }

get_pid_from_file ()
{
  PID=""

  if [ -f "${USR_DIR}/var/run/server.pid" ]
  then
    PID=`cat "${USR_DIR}/var/run/server.pid"`
  else
    PID=""
  fi
}

check_process_list ()
{
  process_list=""

  get_pid_from_file

  if [[ "x${PID}" != "x" ]]
  then
    process_list=`ps -p ${PID} -o pid,command | grep nxserver`
  fi
}

start()
{
  echo "Starting NoMachine."
  ${USR_DIR}/bin/nxexec ${ETC_DIR}/nxserver --daemon & > /dev/null 2>&1
}

stop()
{
  echo "Stopping NoMachine."
  ${ETC_DIR}/nxserver --shutdown > /dev/null 2>&1
}

restart()
{
  stop
  start
}

status()
{
  get_pid_from_file
  
  if [[ "x${PID}" != "x" ]]
  then

    check_process_list

    if [[ "x${process_list}" != "x" ]]
    then
      echo "NoMachine is running (with PID: ${PID})."

      return 0
    else

      if [ -f ${USR_DIR}/var/run/server.pid.lock ]
      then
        echo "NoMachine is not running."

        return 2
      else
        echo "NoMachine is not running."

        return 1
      fi
    fi
  elif [[ "x${PID}" = "x" ]]
  then
    echo "NoMachine is not running."
    return 3
  fi
}

case "$1" in
'start')
  start
  ;;

'stop')
    stop
  ;;

'restart')
    restart
  ;;

'status')
  status
  ;;

*)
  echo "Usage: $0 {start|stop|restart|status}"
  exit 1
  ;;

esac
