#!/bin/bash
# info: change user password
# options: USER PASSWORD
#
# example: v-change-user-password admin NewPassword123
#
# This function changes user's password and updates RKEY value.

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

# Argument definition
user=$1
password=$2
HIDE=2

# 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 [PASSWORD]'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Non-interactive (stdin not opened)
[[ -z "$password" && ! -t 0 ]] && read -r password

# Password prompt
[[ -z "$password" ]] && read -r -s -p "Password:" password

is_password_valid

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Changing user password
echo "$user:$password" | /usr/sbin/chpasswd

if [ $? -ne 0 ]; then
	echo "Error: Password not accepted due to PAM restrictions"
	exit 2
fi

md5=$(awk -v user=$user -F : 'user == $1 {print $2}' /etc/shadow)

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

# Changing RKEY value
update_user_value "$user" '$RKEY' "$(generate_password)"
update_user_value "$user" '$MD5' "$md5"

# Logging
$BIN/v-log-action "system" "Warning" "Security" "Password changed (User: $user)."
$BIN/v-log-action "$user" "Warning" "Security" "Password changed."
log_event "$OK" "$ARGUMENTS"

exit
