#!/bin/bash
# info: change ftp user password.
# options: USER DOMAIN FTP_USER FTP_PASSWORD
#
# example: v-change-web-domain-ftp-password admin example.com ftp_usr ftp_qwerty
#
# This function changes ftp user password.

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

# Argument definition
user=$1
domain=$2
domain_idn=$2
ftp_user=$3
password=$4
HIDE=4

# 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/func/domain.sh
source $HESTIA/func/domain.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

# Additional argument formatting
format_domain
format_domain_idn
# TODO: $domain_idn not used in this script - maybe $domain should be converted to $doman_idn ?

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

check_args '4' "$#" 'USER DOMAIN FTP_USER FTP_PASSWORD'
is_format_valid 'user' 'domain' 'ftp_user'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"
is_password_valid
get_domain_values 'web'
if [ -z "$(echo $FTP_USER | tr ':' '\n' | grep ^$ftp_user$)" ]; then
	echo "Error: account $ftp_user doesn't exist"
	log_event "$E_NOTEXIST" "$ARGUMENTS"
	exit "$E_NOTEXIST"
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

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

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

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

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

# Rebuilding FTP variables
position=$(echo $FTP_USER | tr ':' '\n' | grep -n '' | grep ":$ftp_user$" \
	| cut -f 1 -d:)
ftp_md5=$(echo $FTP_MD5 | tr ':' '\n' | grep -n '' \
	| sed -e "s%^$position:.*%$position:$ftp_md5%" \
	| cut -f 2 -d : | sed -e "/^$/d" | sed -e ':a;N;$!ba;s/\n/:/g')

# Updating config
update_object_value 'web' 'DOMAIN' "$domain" '$FTP_MD5' "$ftp_md5"

# Logging
$BIN/v-log-action "$user" "Info" "Web" "FTP account password changed (User: $ftp_user, Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit