#!/bin/bash
# info: change user random key
# options: USER [HASH]
#
# This function changes user's RKEY value thats has been used for security value to be used forgot password function only.

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

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

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

check_args '1' "$#" 'USER [HASH]'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

if [ -n "$hash" ]; then
	password=$hash
	is_password_valid
	hash=$password
else
	hash=$(generate_password)
fi
#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

d=$(date +%s)

# Changing RKEY value
update_user_value "$user" '$RKEY' "$hash"

#check if RKEYEXP exists
if [ -z "$(grep RKEYEXP $USER_DATA/user.conf)" ]; then
	sed -i "s/^RKEY/RKEYEXP='$d'\nRKEY/g" $USER_DATA/user.conf
else
	update_user_value "$user" '$RKEYEXP' "$d"
fi

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

# Logging
$BIN/v-log-action "system" "Warning" "Users" "Password reset requested (User: $user)."
$BIN/v-log-action "$user" "Warning" "System" "Password reset requested."
log_event "$OK" "$ARGUMENTS"

exit
