#!/bin/bash
# info: add mail domain account
# options: USER DOMAIN ACCOUNT PASSWORD [QUOTA]
#
# The function add new email account.


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

# Argument definition
user=$1
domain=$2
account=$3
password=$4; HIDE=4
quota=${5-unlimited}

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/domain.sh
source $HESTIA/conf/hestia.conf

# Additional argument formatting
if [[ "$account" =~ [[:upper:]] ]]; then
    account=$(echo "$account" |tr '[:upper:]' '[:lower:]')
fi


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

check_args '4' "$#" 'USER DOMAIN ACCOUNT PASSWORD [QUOTA]'
is_format_valid 'user' 'domain' 'account'
if [ "$quota" != 'unlimited' ]; then
    is_format_valid 'quota'
fi
is_system_enabled "$MAIL_SYSTEM" 'MAIL_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'mail' 'DOMAIN' "$domain"
is_object_unsuspended 'mail' 'DOMAIN' "$domain"
is_package_full 'MAIL_ACCOUNTS'
is_mail_new "$account"
is_password_valid

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

# Generating hashed password
salt=$(generate_password "$PW_MATRIX" "8")
md5="{MD5}$($BIN/v-generate-password-hash md5 $salt <<<$password)"

# Adding account info into password file
if [[ "$MAIL_SYSTEM" =~ exim ]]; then
    if [ "$quota" = 'unlimited' ]; then
        quota='0'
    fi
    str="$account:$md5:$user:mail::$HOMEDIR/$user::userdb_quota_rule=*:storage=${quota}M"
    echo $str >> $HOMEDIR/$user/conf/mail/$domain/passwd
fi


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

# Generating timestamp
time_n_date=$(date +'%T %F')
time=$(echo "$time_n_date" |cut -f 1 -d \ )
date=$(echo "$time_n_date" |cut -f 2 -d \ )

if [[ "$quota" -eq '0' ]]; then
    quota='unlimited'
fi

str="ACCOUNT='$account' ALIAS='' AUTOREPLY='no' FWD='' FWD_ONLY=''"
str="$str MD5='$md5' QUOTA='$quota' U_DISK='0' SUSPENDED='no'"
str="$str TIME='$time' DATE='$date'"
echo "$str" >> $USER_DATA/mail/$domain.conf
chmod 660 $USER_DATA/mail/$domain.conf

# Increase mail accounts counter
accounts=$(wc -l $USER_DATA/mail/$domain.conf | cut -f 1 -d ' ')
increase_user_value "$user" '$U_MAIL_ACCOUNTS'
update_object_value 'mail' 'DOMAIN' "$domain" '$ACCOUNTS' "$accounts"

# Logging
log_history "added mail account $account@$domain"
log_event "$OK" "$ARGUMENTS"

exit
