#!/bin/bash
# info: change user name servers
# options: USER NS1 NS2 [NS3] [NS4] [NS5] [NS6] [NS7] [NS8]
#
# example: v-change-user-ns ns1.domain.tld ns2.domain.tld
#
# This function for changing default name servers for specific user.

#----------------------------------------------------------#
#                Variables & Functions                     #
#----------------------------------------------------------#

# Argument definition
user=$1
ns1=$(echo "$2" | sed -e 's/\.*$//g' -e 's/^\.*//g')
ns2=$(echo "$3" | sed -e 's/\.*$//g' -e 's/^\.*//g')
ns3=$(echo "$4" | sed -e 's/\.*$//g' -e 's/^\.*//g')
ns4=$(echo "$5" | sed -e 's/\.*$//g' -e 's/^\.*//g')
ns5=$(echo "$6" | sed -e 's/\.*$//g' -e 's/^\.*//g')
ns6=$(echo "$7" | sed -e 's/\.*$//g' -e 's/^\.*//g')
ns7=$(echo "$8" | sed -e 's/\.*$//g' -e 's/^\.*//g')
ns8=$(echo "$9" | sed -e 's/\.*$//g' -e 's/^\.*//g')

# Includes
# shellcheck source=/etc/tuliocp/tulio.conf
source /etc/tuliocp/tulio.conf
# shellcheck source=/usr/local/tulio/func/main.sh
source $TULIO/func/main.sh
# load config file
source_conf "$TULIO/conf/tulio.conf"

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

# Checking args
check_args '3' "$#" 'USER NS1 NS2 [NS3] [NS4] [NS5] [NS6] [NS7] [NS8]'

# Checking argument format
is_format_valid 'user' 'ns1' 'ns2'

if [ "$ns1" = '' ]; then
	check_result '3' "Usage: v-change-user-ns USER NS1 NS2 [NS3] [NS4] [NS5] [NS6] [NS7] [NS8]"
fi
if [ "$ns2" = '' ]; then
	check_result '3' "Usage: v-change-user-ns USER NS1 NS2 [NS3] [NS4] [NS5] [NS6] [NS7] [NS8]"
fi

ns="$ns1,$ns2"
if [ -n "$ns3" ]; then
	is_format_valid 'ns3'
	ns="$ns,$ns3"
fi
if [ -n "$ns4" ]; then
	is_format_valid 'ns4'
	ns="$ns,$ns4"
fi
if [ -n "$ns5" ]; then
	is_format_valid 'ns5'
	ns="$ns,$ns5"
fi
if [ -n "$ns6" ]; then
	is_format_valid 'ns6'
	ns="$ns,$ns6"
fi
if [ -n "$ns7" ]; then
	is_format_valid 'ns7'
	ns="$ns,$ns7"
fi
if [ -n "$ns8" ]; then
	is_format_valid 'ns8'
	ns="$ns,$ns8"
fi
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_tulio_demo_mode

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

# Changing ns values
update_user_value "$user" '$NS' "$ns"

#----------------------------------------------------------#
#                       Tulio                             #
#----------------------------------------------------------#

# Logging
$BIN/v-log-action "$user" "Info" "DNS" "Updated DNS nameservers ($ns1 $ns2 $ns3 $ns4 $ns5 $ns6 $ns7 $ns8)."
log_event "$OK" "$ARGUMENTS"

exit
