#!/bin/bash
# info: add system web terminal
# options: NONE
#
# example: v-add-sys-web-terminal
#
# This function enables the web terminal.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Includes
# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

if [ "$WEB_TERMINAL" = 'true' ]; then
	exit
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Updating WEB_TERMINAL value
$BIN/v-change-sys-config-value "WEB_TERMINAL" "true"

# Detect and install Node.js if necessary
apt="/etc/apt/sources.list.d"
node_v="20"

if [ $(uname -m) = "x86_64" ]; then
	ARCH=amd64
elif [ $(uname -m) = "aarch64" ]; then
	ARCH=arm64
fi

if [ -z $(which "node") ]; then
	echo "Installing Node.js $node_v"
	echo "deb [arch=$ARCH signed-by=/usr/share/keyrings/nodejs.gpg] https://deb.nodesource.com/node_$node_v.x nodistro main" > $apt/nodejs.list
	curl -s https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor | tee /usr/share/keyrings/nodejs.gpg > /dev/null 2>&1
	apt-get -qq install nodejs -y
else
	node_v_installed=$(/usr/bin/node -v | cut -f1 -d'.' | sed 's/v//g')
	if [ "$node_v_installed" -lt "$node_v" ]; then
		echo "Web Terminal requires Node.js $node_v or latest"
		exit 1
	fi
fi

if [ ! -f "$HESTIA/web-terminal/server.js" ]; then
	apt-get -qq update
	apt-get -qq install hestia-web-terminal -y
else
	# Starting web terminal websocket server
	$BIN/v-start-service "hestia-web-terminal"
	systemctl enable hestia-web-terminal
fi

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

# Logging
$BIN/v-log-action "system" "Info" "Web Terminal" "Web terminal enabled."
log_event "$OK" "$ARGUMENTS"

exit
