#!/bin/bash
# info: synchronize dns domains
# options: HOST
# The function synchronize all dns domains.


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

# Argument definition
host=$1

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


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

is_system_enabled "$DNS_CLUSTER" 'DNS_CLUSTER'
is_procces_running
remote_dns_health_check 'no_email'


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

# Selecting remote hosts
IFS=$'\n'
if [ -z $host ]; then
    hosts=$(cat $VESTA/conf/dns-cluster.conf |grep "SUSPENDED='no'")
else
    hosts=$(grep "HOST='$host'" $VESTA/conf/dns-cluster.conf)
fi

# Starting cluster loop
for cluster in $hosts; do

    # Parsing host values
    eval $cluster

    # Wiping remote domains
    cluster_cmd v-delete-dns-domains-src $DNS_USER $HOSTNAME no
    check_result $? "$HOST connection failed" $E_CONNECT

    # Syncing user domains
    user_list=$(ls -d $VESTA/data/users/*/ | sed "s#$VESTA/data/users/##" | sed s"/.$//" | grep -v "dns-cluster")
    for user in $user_list; do
        for str in $(cat $VESTA/data/users/$user/dns.conf); do

            # Syncing domain index
            eval $str
            cluster_cmd v-insert-dns-domain $DNS_USER "$str" $HOSTNAME ' ' no
            check_result $? "$HOST connection failed" $E_CONNECT

            # Syncing domain records
            tmp_file="/tmp/vst-sync.$DOMAIN"
            cluster_file $USER_DATA/$user/dns/$DOMAIN.conf $tmp_file
            check_result $? "$HOST connection failed" $E_CONNECT

            cluster_cmd v-insert-dns-records $DNS_USER $DOMAIN $tmp_file 'no'
            check_result $? "$HOST connection failed" $E_CONNECT
        done
    done

    # Rebuilding dns zones
    cluster_cmd v-rebuild-dns-domains $DNS_USER
    check_result $? "$TYPE connection to $HOST failed" $E_CONNECT

done


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

# Flushing dns-cluster queue
rm -f $VESTA/data/queue/dns-cluster.pipe
touch $VESTA/data/queue/dns-cluster.pipe
chmod 660 $VESTA/data/queue/dns-cluster.pipe

exit
