#!/bin/sh -e

memory="$(cat "${__global}/explorer/memory")"
G="000000"  # Will totally eff up the zero-count otherwise
# MAX_MEMORY will affect jicofo and videobridge
#  As a rule of thumb, the machine's RAM should be more than 2.5 * MAX_MEMORY
if [ "${memory}" -lt "3${G}" ]; then
	# If you use this, let us know how it works!
	MAX_MEMORY="768m"
elif [ "${memory}" -lt "5${G}" ]; then
	MAX_MEMORY="1024m"
elif [ "${memory}" -lt "8${G}" ]; then
	MAX_MEMORY="2048m"
else
	# Jitsi recommends running on 8G RAM and these are the defaults
	MAX_MEMORY="3072m"
fi

if cut -f 2 "${__object}/explorer/configured-memory" | grep -qvE "^${MAX_MEMORY}$"; then
	# At least one service has different memory settings
	RESTART_SERVICES="YES"
	cat <<-EOF
	sed -i.tmp -E \
		-e 's!^(#[[:space:]]*)?(VIDEOBRIDGE_MAX_MEMORY)=.*\$!\2=${MAX_MEMORY}!' \
		/usr/share/jitsi-videobridge/lib/videobridge.rc
	sed -i.tmp -E \
		-e 's!(JICOFO_MAX_MEMORY)[^";]+;!\1=${MAX_MEMORY};!' \
		/usr/share/jicofo/jicofo.sh
	EOF
fi

if grep -qE "^__file/etc/nginx" "${__messages_in}"; then
	echo "service nginx reload"
fi

if grep -qE "^(__line/jitsi_jicofo_secured_domains|(__file|__link)/etc/prosody/conf.d/|__file/etc/jitsi/(jicofo/jicofo.conf|videobridge/jvb.conf))" "${__messages_in}"; then
	RESTART_SERVICES="YES"
fi

if [ -n "${RESTART_SERVICES}" ]; then
  echo "systemctl restart prosody"
  echo "systemctl restart jicofo"
  echo "systemctl restart jitsi-videobridge2"
fi
