#!/bin/bash
# info: insert dns domain
# options: USER DATA [SRC] [FLUSH] #
# This function inserts raw record to the dns.conf

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

# Argument definition
user=$1
data=$2
src=$3
flush=$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 '2' "$#" 'USER DATA [SRC] [FLUSH] [RESTART]'
is_format_valid 'user' 'data'
is_system_enabled "$DNS_SYSTEM" 'DNS_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
parse_object_kv_list "$data"

domain="$DOMAIN"
if [ -z "$domain" ]; then
	check_result $E_ARGS "Domain name missing from DATA"
fi
is_format_valid 'domain'

if [ "$flush" = 'no' ]; then
	is_domain_new 'dns' $domain
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Flush records
if [ "$flush" = 'records' ]; then
	rm -f $USER_DATA/dns/$DOMAIN.conf
	touch $USER_DATA/dns/$DOMAIN.conf
	chmod 660 $USER_DATA/dns/$DOMAIN.conf
fi

# Flush domain
if [ "$flush" != 'no' ]; then
	sed -i "/DOMAIN='$DOMAIN'/d" $USER_DATA/dns.conf 2> /dev/null
fi

# Generating timestamp
time_n_date=$(date +'%T %F')
time=$(echo "$time_n_date" | cut -f 1 -d \ )
date=$(echo "$time_n_date" | cut -f 2 -d \ )

# Prepare values for the insert
dns_rec="DOMAIN='$DOMAIN' IP='$IP' TPL='$TPL' TTL='$TTL' EXP='$EXP'"
dns_rec="$dns_rec SOA='$SOA' SERIAL='$SERIAL' SRC='$src' RECORDS='$RECORDS'"
dns_rec="$dns_rec DNSSEC='$DNSSEC' KEY='$KEY' SLAVE='$SLAVE' MASTER='$MASTER'"
dns_rec="$dns_rec SUSPENDED='$SUSPENDED' TIME='$time' DATE='$date'"
echo "$dns_rec" >> $USER_DATA/dns.conf

if [ "$SLAVE" = "yes" ]; then
	touch $USER_DATA/dns/$domain.conf
fi
# Set permission
chmod 660 $USER_DATA/dns.conf

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit
