#!/bin/bash
# info: add dns domain or dns record after web domain alias
# options: USER ALIAS IP [RESTART]
#
# example: v-add-dns-on-web-alias admin www.example.com 8.8.8.8
#
# This function adds dns domain or dns record based on web domain alias.

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

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

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

check_args '3' "$#" 'USER ALIAS IP [RESTART]'
is_format_valid 'user' 'alias' 'ip' 'restart'
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

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

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

# No logging

exit
