#!/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 defenition
host=$1
port=$2
user=$3
password=$4
type=${5-api}
dns_user=${6-dns-cluster}

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

# Hiding passwords
A4='******'


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

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


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

# Concatentating db host string
str="HOST='$host' USER='$user' PASSWORD='$password' DNS_USER='$dns_user'"
str="$str TYPE='$type' SUSPENDED='no' TIME='$TIME' DATE='$DATE'"

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

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

# Enabling restart queue
HOST=$host
PORT=$port
USER=$user
PASSWORD=$password
case $type in
    ssh) send_cmd="send_ssh_cmd" ;;
    *)  send_cmd="send_api_cmd" ;;
esac
$send_cmd v-add-cron-restart-job

# Sync current zones
$BIN/v-sync-dns-cluster $host
return_code=$?
if [ "$return_code" -ne 0 ]; then
    exit $return_code
fi

# Add dns-cluster cron job
cmd="sudo /usr/local/vesta/bin/v-update-sys-queue dns-cluster"
check_cron=$(grep "$cmd" $VESTA/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


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

# Logging
log_event "$OK" "$EVENT"

exit
