#!/bin/bash
# info: add dns domain or dns record after web domain alias
# options: USER ALIAS IP [RESTART]
#
# The function adds dns domain or dns record based on web domain alias.


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

# Argument definition
user=$1
alias=$2
ip=$3
restart=$4

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


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

check_args '3' "$#" 'USER ALIAS IP [RESTART]'
is_format_valid 'user' 'alias' 'ip'
is_system_enabled "$DNS_SYSTEM" 'DNS_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
if [ -e "$USER_DATA/dns/$alias.conf" ]; then
    exit
fi


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

# Logging
log_event "$OK" "$ARGUMENTS"

# Define additional vars
sub_domain=$(echo "$alias" |awk -F '.' '{print $1}')
top_domain=$(echo "$alias" |sed -e "s/^$sub_domain.//")
domain_lvl=$(echo "$alias" |grep -o "\." |wc -l)

# Adding second level domain
if [ "$domain_lvl" -eq 1 ] || [ "${#top_domain}" -le '6' ]; then
    $BIN/v-add-dns-domain \
        $user $alias $ip '' '' '' '' '' '' '' '' $restart >> /dev/null
    exit
fi

# Adding top-level domain and then its sub
$BIN/v-add-dns-domain $user $top_domain $ip '' '' '' '' '' '' '' '' $restart >> /dev/null

# Checking top-level domain
if [ ! -e "$USER_DATA/dns/$top_domain.conf" ]; then
    exit
fi

# Checking subdomain record
if [ "$sub_domain" == '*' ]; then
    check_record=$(grep -w "RECORD='\*'" $USER_DATA/dns/$top_domain.conf)
else
    check_record=$(grep -w "RECORD='$sub_domain'" $USER_DATA/dns/$top_domain.conf)
fi

# Adding subdomain record
if [ -z "$check_record" ]; then
    $BIN/v-add-dns-record \
        $user $top_domain "$sub_domain" A $ip '' '' $restart >> /dev/null
fi


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

# No logging

exit