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


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

# Argument definition
user=$1
data=$2
src=$3
flush=$4
restart=$5

# Includes
source $VESTA/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/conf/vesta.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"
eval $data
domain="$DOMAIN"
if [ "$flush" = 'no' ]; then
    is_domain_new 'dns' $domain
fi


#----------------------------------------------------------#
#                       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 SUSPENDED='$SUSPENDED' TIME='$time' DATE='$date'"
echo "$dns_rec" >> $USER_DATA/dns.conf

# Set permission
chmod 660 $USER_DATA/dns.conf


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

# Restarting named
$BIN/v-restart-dns $restart
check_result $? "Bind restart failed" >/dev/null

# Logging
log_event "$OK" "$ARGUMENTS"

exit
