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


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

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
domain_idn=$(idn -t --quiet -a "$domain")
ftp_user=$3
ftp_password=$4

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


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

check_args '4' "$#" 'USER DOMAIN FTP_USER FTP_PASSWORD'
validate_format 'user' 'domain' 'ftp_user' 'ftp_password'
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"
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" "$EVENT"
    exit $E_NOTEXIST
fi


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

# Changing ftp user password
echo "$ftp_user:$ftp_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" "$EVENT"

exit
