#!/bin/bash
# info: change user password
# options: USER PASSWORD
#
# The function changes user's password and updates RKEY value.


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

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

# Importing system enviroment as we run this script
# mostly by cron wich not read it by itself
source /etc/profile

# Includes
source $VESTA/func/main.sh
source $VESTA/conf/vesta.conf


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

if [ "$user" = "root" ]; then
    check_result $E_FORBIDEN "Changing root password is forbiden"
fi
check_args '2' "$#" 'USER PASSWORD'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_password_valid


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

# Changing user password
echo "$user:$password" | /usr/sbin/chpasswd
md5=$(awk -v user=$user -F : 'user == $1 {print $2}' /etc/shadow)

if [ "$user" = 'admin' ] && [ -e "$VESTA/web/reset.admin" ]; then
    rm -f $VESTA/web/reset.admin
fi


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

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

# Logging
log_history "changed password"
log_event "$OK" "$ARGUMENTS"

exit
