#!/bin/bash
# info: change sysconfig value
# options: KEY VALUE
#
# example: v-change-sys-config-value VERSION 1.0
#
# This function is for changing main config settings such as COMPANY_NAME or
# COMPANY_EMAIL and so on.

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

# Argument definition
key=$(echo "$1" | tr '[:lower:]' '[:upper:]')
value=$2

# 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"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

check_args '2' "$#" 'KEY VALUE'
is_common_format_valid "$key" 'key'
format_no_quotes "$value" 'value'
#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

change_sys_value "$key" "$value"

# Sort configuration file in alphabetical order on change
sort $HESTIA/conf/hestia.conf -o /tmp/updconf
mv $HESTIA/conf/hestia.conf $HESTIA/conf/hestia.conf.bak
mv /tmp/updconf $HESTIA/conf/hestia.conf
rm -f $HESTIA/conf/hestia.conf.bak

# Check if the variable "$key" has the value "APP_NAME"
if [ "$key" == "APP_NAME" ]; then
	# Path to the file manager configuration file where the change will be made.
	config_file="$HESTIA/web/fm/configuration.php"
	new_app_name="File Manager - $value"

	# Verify if configuration.php exists and is writable
	if [ -f "$config_file" ] && [ -w "$config_file" ]; then
		# Sed replaces only the value after "File Manager -"
		sed -i "s|\(\$dist_config\[\"frontend_config\"\]\[\"app_name\"\] = \"File Manager - \).*\";|\1${value}\";|" "$config_file"
	fi
fi

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

# Logging
$BIN/v-log-action "system" "Info" "System" "System configuration value changed (Key: $key, Value: $value)."
log_event "$OK" "$ARGUMENTS"

exit
