#!/bin/bash
# info: updates user theme
# options: USER THEME
#
# example:   v-change-user-theme admin dark
# example:   v-change-user-theme peter vestia
#
# Changes web UI display theme for specified user.

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

# Argument definition
user=$1
theme=$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
# shellcheck source=/usr/local/hestia/conf/hestia.conf
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

is_format_valid 'user' 'theme'
is_common_format_valid "$theme" "theme"
is_object_valid 'user' 'USER' "$user"

is_object_unsuspended 'user' 'USER' "$user"

themes=$($BIN/v-list-sys-themes plain)

if ! echo "$themes" | grep -q -x "$theme"; then
	echo "Theme does not exists"
	exit "$E_NOTEXIST"
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Set theme value
check_ckey=$(grep "THEME" $USER_DATA/user.conf)
if [ -z "$check_ckey" ]; then
	# Rebuild user configuration to repair missing value
	$BIN/v-rebuild-user "$user"
fi
update_user_value "$user" '$THEME' "$theme"

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

# Logging
$BIN/v-log-action "$user" "Info" "System" "Applied theme to user interface (Theme: $theme)."

exit