#!/bin/bash
# info: add web/dns/mail domain
# options: USER DOMAIN [IP] [RESTART]
#
# example: v-add-domain admin example.com
#
# This function adds web/dns/mail domain to a server.

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

# Argument definition
user=$1
domain=$2
ip=$3
restart=$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/ip.sh
source $HESTIA/func/ip.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#
check_args '2' "$#" 'USER DOMAIN [IP] [RESTART]'
is_format_valid 'user' 'domain' 'restart'
if [ -n "$ip" ]; then
	is_format_valid 'ip'
fi
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Get ip if it wasn't defined
if [ -z "$ip" ]; then
	get_user_ip
	if [ -z "$ip" ]; then
		check_result "$E_NOTEXIST" "no available IP address"
	fi
fi

# Working on web domain
if [ -n "$WEB_SYSTEM" ]; then
	check1=$(is_package_full 'WEB_DOMAINS')
	if [ $? -eq 0 ]; then
		$BIN/v-add-web-domain "$user" "$domain" "$ip" 'no'
		check_result $? "can't add web domain"
	fi
fi

# Working on DNS domain
if [ -n "$DNS_SYSTEM" ]; then
	check2=$(is_package_full 'DNS_DOMAINS')
	if [ $? -eq 0 ]; then
		$BIN/v-add-dns-domain "$user" "$domain" "$ip" "" "" "" "" "" "" "" "" "no"
		check_result $? "can't add dns domain"
	fi
fi

# Working on mail domain
if [ -n "$MAIL_SYSTEM" ]; then
	check3=$(is_package_full 'MAIL_DOMAINS')
	if [ $? -eq 0 ]; then
		$BIN/v-add-mail-domain $user $domain 'no'
		check_result $? "can't add mail domain"
	fi
fi

if [[ "$check1" != '' && "$check2" != '' && "$check3" != '' ]]; then
	check_result 8 "Package limit reached"
fi

# Restarting services
$BIN/v-restart-web "$restart"
check_result $? "can't restart web" > /dev/null

$BIN/v-restart-proxy "$restart"
check_result $? "can't restart proxy" > /dev/null

$BIN/v-restart-dns "$restart"
check_result $? "can't restart dns" > /dev/null

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

exit