#!/bin/bash
# info: change ftp user password.
# options: USER DOMAIN FTP_USER FTP_PASSWORD
#
# The function changes ftp user password.


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

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

# Includes
source $VESTA/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/conf/vesta.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


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

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


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

# 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
log_history "changed password for $ftp_user on $domain"
log_event "$OK" "$ARGUMENTS"

exit
