#!/bin/bash
# info: change dns domain template
# options: USER DOMAIN TEMPLATE [RESTART]
#
# The function for changing the template of records. By updating old records
# will be removed and new records will be generated in accordance with
# parameters of new template.


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

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
domain_idn=$(idn -t --quiet -a "$domain")
template=$3
restart=$4

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


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

check_args '3' "$#" 'USER DOMAIN TEMPLATE [RESTART]'
validate_format 'user' 'domain' 'template'
is_system_enabled "$DNS_SYSTEM" 'DNS_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'dns' 'DOMAIN' "$domain"
is_object_unsuspended 'dns' 'DOMAIN' "$domain"
is_dns_template_valid


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

# Defining variables
ip=$(get_object_value 'dns' 'DOMAIN' "$domain" '$IP')

i=1
ns=$(get_user_value '$NS')
for nameserver in ${ns//,/ };do
    eval ns$i=$nameserver
    (( ++i))
done

# Changing tpl
cat $DNSTPL/$template.tpl |\
    sed -e "s/%ip%/$ip/g" \
        -e "s/%domain_idn%/$domain_idn/g" \
        -e "s/%domain%/$domain/g" \
        -e "s/%ns1%/$ns1/g" \
        -e "s/%ns2%/$ns2/g" \
        -e "s/%ns3%/$ns3/g" \
        -e "s/%ns4%/$ns4/g" \
        -e "s/%time%/$TIME/g" \
        -e "s/%date%/$DATE/g" > $USER_DATA/dns/$domain.conf
records="$(wc -l $USER_DATA/dns/$domain.conf |cut -f 1 -d ' ')"

# Updating zone
if [[ "$DNS_SYSTEM" =~ named|bind ]]; then
    update_domain_zone
fi

# Updating dns-cluster queue
if [ ! -z "$DNS_CLUSTER" ]; then
    # Check for first sync
    dlock=$(grep "domain $user $domain" $VESTA/data/queue/dns-cluster.pipe)
    if [ -z "$dlock" ]; then
        cmd="$BIN/v-add-remote-dns-domain $user $domain domain"
        echo "$cmd" >> $VESTA/data/queue/dns-cluster.pipe
    fi
fi


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

# Updating vesta config
update_object_value 'dns' 'DOMAIN' "$domain" '$TPL' "$template"
update_object_value 'dns' 'DOMAIN' "$domain" '$RECORDS' "$records"

# Restart named
if [ "$restart" != 'no' ]; then
    $BIN/v-restart-dns
    if [ $? -ne 0 ]; then
        exit $E_RESTART
    fi
fi

# Logging
log_history "changed dns template for $domain to $template" '' 'admin'
log_event "$OK" "$EVENT"

exit
