#!/bin/bash
# info: change user language
# options: USER LANGUAGE
#
# example: v-change-user-language admin en
#
# This function for changing language.

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

# Argument definition
user=$1
language=$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"

is_language_valid() {
	# English is always allowed
	if [ "$1" != "en" ]; then
		if ! [[ "$1" =~ ^[[:alnum:]_-]+$ ]]; then
			echo "Error: language $1 is not valid"
			log_event "$E_INVALID" "$ARGUMENTS"
			exit $E_INVALID
		fi
		if [ ! -d "$HESTIA/web/locale/$1" ]; then
			echo "Error: language $1 doesn't exist"
			log_event "$E_NOTEXIST" "$ARGUMENTS"
			exit $E_NOTEXIST
		fi
	fi
}

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

check_args '2' "$#" 'USER LANGUAGE'
is_format_valid 'user' 'language'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_language_valid "$language"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Change language
if [ -z "$(grep LANGUAGE $USER_DATA/user.conf)" ]; then
	sed -i "s/^TIME/LANGUAGE='$language'\nTIME/g" $USER_DATA/user.conf
else
	update_user_value "$user" '$LANGUAGE' "$language"
fi

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

# Logging
$BIN/v-log-action "$user" "Info" "System" "Display language changed (Value: $language)."
log_event "$OK" "$ARGUMENTS"

exit
