#!/bin/bash
# info: add web/dns/mail domain
# options: USER DOMAIN [IP] [RESTART]
#
# The function adds web/dns/mail domain to a server.


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

# Argument definition
user=$1
domain=$2
ip=$3
restart="${4-yes}"

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


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


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

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

# Working on web domain
if [ ! -z "$WEB_SYSTEM" ]; then
    $BIN/v-add-web-domain $user $domain $ip 'no'
    check_result $? "can't add web domain" >/dev/null
fi

# Working on DNS domain
if [ ! -z "$DNS_SYSTEM" ]; then
    $BIN/v-add-dns-domain $user $domain $ip "" "" "" "" "" '' '' '' 'no'
    check_result $? "can't add dns domain" >/dev/null
fi

# Working on mail domain
if [ ! -z "$MAIL_SYSTEM" ]; then
    $BIN/v-add-mail-domain $user $domain
    check_result $? "can't add mail domain" >/dev/null
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


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

exit
