#!/bin/bash
# info: add mail domain account
# options: USER DOMAIN ACCOUNT PASSWORD [QUOTA]
#
# example: v-add-mail-account user example.com john P4$$vvOrD
#
# This function add new email account.

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

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

# 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
# shellcheck source=/usr/local/hestia/func/syshealth.sh
source $HESTIA/func/syshealth.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

format_domain
format_domain_idn

#----------------------------------------------------------#
#                    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

if [ -n "$(doveadm pw -l | grep BLF-CRYPT)" ]; then
	set +H # disable ! style history substitution
	md5="$(doveadm pw -s BLF-CRYPT -p "$password")"
elif [ -n "$(doveadm pw -l | grep ARGON2ID)" ]; then
	# Fall back on Argon2id if bcrypt is not available
	set +H # disable ! style history substitution
	md5="$(doveadm pw -s ARGON2ID -p "$password")"
else
	# Fall back on MD5 if neither bcrypt nor argon2id is available
	salt=$(generate_password "$PW_MATRIX" "8")
	md5="{MD5}$($BIN/v-generate-password-hash md5 $salt <<< $password)"
fi
# 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:${quota}:userdb_quota_rule=*:storage=${quota}M"
	echo $str >> $HOMEDIR/$user/conf/mail/$domain/passwd
	userstr="$account:$account:$user:mail:$HOMEDIR/$user"
	echo $userstr >> $HOMEDIR/$user/conf/mail/$domain/accounts
fi

# Create mail account folder (mailbox)
mkdir $HOMEDIR/$user/mail/$domain_idn/$account
chown $user:mail $HOMEDIR/$user/mail/$domain_idn/$account
chmod 700 $HOMEDIR/$user/mail/$domain_idn/$account

#----------------------------------------------------------#
#                       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

syshealth_repair_mail_account_config

touch $HOMEDIR/$user/conf/mail/$domain/limits

user_rate_limit=$(get_object_value 'mail' 'DOMAIN' "$domain" '$RATE_LIMIT')
if [ -n "$user_rate_limit" ]; then
	sed -i "/^$account@$domain_idn:/ d" $HOMEDIR/$user/conf/mail/$domain/limits
	echo "$account@$domain_idn:$user_rate_limit" >> $HOMEDIR/$user/conf/mail/$domain/limits
else
	system=$(cat /etc/exim4/limit.conf)
	sed -i "/^$account@$domain_idn:/ d" $HOMEDIR/$user/conf/mail/$domain/limits
	echo "$account@$domain_idn:$system" >> $HOMEDIR/$user/conf/mail/$domain/limits
fi

# 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
$BIN/v-log-action "$user" "Info" "Mail" "Added new mail account ($account@$domain)."
log_event "$OK" "$ARGUMENTS"

exit