#!/bin/bash
# info: change user contact email
# options: USER EMAIL
#
# example: v-change-user-contact admin admin@yahoo.com
#
# This function for changing of e-mail associated with a certain user.

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

# Argument definition
user=$1
email=$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 '2' "$#" 'USER EMAIL'
is_format_valid 'user' 'email'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Changing user contact email
old_email=$(get_user_value '$CONTACT')
update_user_value "$user" '$CONTACT' "$email"
pw_str=$(grep -n "^$user:" /etc/passwd)
str=$(echo "$pw_str" | cut -f 1 -d :)
sed -i "$str s/$old_email/$email/g" /etc/passwd

# Update crontab email
$BIN/v-rebuild-cron-jobs "$user" > /dev/null 2>&1

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

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

exit
