#!/bin/bash
# info: delete dns domain or dns record based on web domain alias
# options: USER DOMAIN ALIAS [RESTART]
#
# example: v-delete-dns-on-web-alias admin example.com www.example.com
#
# This function deletes dns domain or dns record based on web domain alias.

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

# Argument definition
user=$1
domain=$2
alias=$3
domain_idn=$2
dom_alias=$(idn2 --quiet -d "$3")
dom_alias=$(echo $dom_alias | sed -e 's/\.*$//g' -e 's/^\.*//g')
dom_alias=$(echo $dom_alias | tr '[:upper:]' '[:lower:]')
dom_alias_idn=$(idn2 --quiet "$dom_alias")
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"

# Additional argument formatting
format_domain
format_domain_idn
# TODO: $domain_idn not used in this script - maybe $domain should be converted to $doman_idn ?

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

check_args '3' "$#" 'USER DOMAIN ALIAS [RESTART]'
is_format_valid 'user' 'domain' 'alias' 'restart'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_system_enabled "$DNS_SYSTEM" 'DNS_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Parsing domain values
get_domain_values 'web'

# Check if it a simple domain
if [ $(echo -e "${dom_alias//\./\n}" | wc -l) -le 2 ]; then
	if [ -e "$USER_DATA/dns/$dom_alias.conf" ]; then
		$BIN/v-delete-dns-domain $user $dom_alias $IP $restart
	fi
else
	# Check subdomain
	sub=$(echo "$dom_alias" | cut -f1 -d . -s)
	root=$(echo "$dom_alias" | sed "s/^$sub.//")
	if [ -e "$USER_DATA/dns/$root.conf" ]; then
		if [ "$sub" == '*' ]; then
			rec=$(grep -w "RECORD='\*'" $USER_DATA/dns/$root.conf)
		else
			rec=$(grep -w "RECORD='$sub'" $USER_DATA/dns/$root.conf)
		fi
		if [ -n "$rec" ]; then
			parse_object_kv_list "$rec"
			$BIN/v-delete-dns-record "$user" "$root" "$ID" "$restart"
		fi
	fi
fi

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit
