#!/bin/bash

SCRIPT_VER="1.4"

APP="NoMachine"
APP_CATEGORY="Remote Access"
APP_SCOPE="system"
APP_ENABLED="yes"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu24.04"
LIBRARY="functions4.sh"

if [ "${SUPPORT-}" = '' ]; then
    SUPPORT="https://installers.rapidseedbox.com/scripts/whmcs_client_installers/support"
fi

LOGFILE="/var/log/whmcs_client_installers/${0}.log"
[ ! -d "/var/log/whmcs_client_installers" ] && mkdir -p "/var/log/whmcs_client_installers"

wget -4 -nc -q --no-check-certificate --timeout=20 --tries=5 ${SUPPORT}/${LIBRARY} >> "${LOGFILE}" 2>&1
if [ ! -f "./${LIBRARY}" ] ; then
    echo "55"
    echo "Error downloading \"${SUPPORT}/${LIBRARY}\"" >> "${LOGFILE}"
    exit 55
fi

# shellcheck source=support/functions4.sh
. "./${LIBRARY}"
SCRIPTENTRY

#
# -- https://www.nomachine.com/download
#
#NOMACHINE_VER="6.0.78_1"
#NOMACHINE_VER="6.1.6_9"
#NOMACHINE_VER="6.2.4_1"
#NOMACHINE_VER="6.3.6_1"
NOMACHINE_VER="6.12.3_7"
#NOMACHINE_VER="7.9.2_1"

while : ; do

    main_rc=1

    CHECK_APP ; _rc=$?
    if [ ${_rc} -ne 0 ] ; then
        main_rc=${_rc}
        break
    fi

    ${PKG_INSTALL} "pulseaudio" || break

    WGET "${SUPPORT}/nomachine/nomachine_${NOMACHINE_VER}_amd64.deb" || break
    ${PKG_INSTALL} "${TMP_DIR}/nomachine_${NOMACHINE_VER}_amd64.deb" || break

    SVC_STOP "nxserver"
    RUN_LOG "sed -i -e 's/^#PhysicalDesktopAuthorization.*$/PhysicalDesktopAuthorization 0/' \
              '/usr/NX/etc/server.cfg'"
    RUN_LOG "sed -i -e 's/^#SSHDPort.*$/SSHDPort 2222/' \
              '/usr/NX/etc/server.cfg'"
    RUN_LOG "sed -i -e 's/^#EnablePersistentSession.*$/EnablePersistentSession \"\"/' \
              '/usr/NX/etc/server.cfg'"
    RUN_LOG "sed -i -e 's/^.*ClientConnectionMethods.*$/ClientConnectionMethods NX/' \
              '/usr/NX/etc/server.cfg'"
    SVC_START "nxserver"

    # `monit` configuration
    if [ -e "/etc/monit/conf.d" ] ; then
        cat <<-EOF > "/etc/monit/conf.d/nxserver"
	check process nxserver with pidfile /usr/NX/var/run/nxserver.pid
	  start program = "/usr/sbin/service nxserver restart &"
	  stop program = "/usr/sbin/service nxserver stop &"

	#check process nxd with pidfile /usr/NX/var/run/nxd.pid
	#  start program = "/usr/sbin/service nxserver restart &"
	#  stop program = "/usr/sbin/service nxserver stop &"
	EOF
        MONIT_RELOAD
    fi


    main_rc=0
    break

done

SCRIPTEXIT
