#!/bin/bash
# info: add new remote dns host
# options: HOST PORT USER PASSWORD [TYPE] [DNS_USER]
#
# The function adds remote dns server to the dns cluster.


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

# Argument definition
host=$1
HOST=$host
port=$2
PORT=$port
user=$3
USER=$user
password=$4; HIDE=4
PASSWORD=$password
type=${5-api}
TYPE="$type"
dns_user=${6-dns-cluster}
DNS_USER=$dns_user

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/remote.sh
source $HESTIA/conf/hestia.conf


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

args_usage='HOST PORT USER PASSWORD [TYPE] [DNS_USER]'
check_args '4' "$#" "$args_usage"
is_format_valid 'host' 'port' 'user' 'type' 'dns_user'
is_system_enabled "$DNS_SYSTEM" 'DNS_SYSTEM'
is_password_valid
is_dnshost_new
is_dnshost_alive


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

# 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 \ )

# Concatentating dns host string
str="HOST='$host' PORT='$port' USER='$user' PASSWORD='$password'"
str="$str DNS_USER='$dns_user' TYPE='$type' SUSPENDED='no'"
str="$str TIME='$time' DATE='$date'"

# Adding host to dns-cluster.conf
echo "$str" >> $HESTIA/conf/dns-cluster.conf
chmod 660 $HESTIA/conf/dns-cluster.conf

# Enabling DNS_CLUSTER
if [ -z "$(grep DNS_CLUSTER $HESTIA/conf/hestia.conf)" ]; then
    sed -i "s/^STATS_/DNS_CLUSTER='yes'\nSTATS_/g" $HESTIA/conf/hestia.conf
else
    sed -i "s/DNS_CLUSTER=.*/DNS_CLUSTER='yes'/g" $HESTIA/conf/hestia.conf
fi

# Enabling remote dns-cluster queue
cluster_cmd v-add-cron-restart-job
check_result $? "$HOST connection failed" $E_CONNECT

# Syncing all domains
$BIN/v-sync-dns-cluster $host
check_result $? "$HOST sync failed" $E_CONNECT


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

# Adding local  dns-cluster cron job
cmd="sudo $HESTIA/bin/v-update-sys-queue dns-cluster"
check_cron=$(grep "$cmd" $HESTIA/data/users/admin/cron.conf 2> /dev/null)
if [ -z "$check_cron" ] && [ ! -z "$CRON_SYSTEM" ]; then
    $BIN/v-add-cron-job admin '*/5' '*' '*' '*' '*' "$cmd"
fi

# Logging
log_event "$OK" "$ARGUMENTS"

exit
