#!/bin/bash
# info: delete system ip
# options: ip
#
# The function for deleting a system ip. It does not allow to delete first ip
# on interface and do not allow to delete ip which is used by a web domain.


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

# Argument defenition
ip=$1

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


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

check_args '1' "$#" 'ip'
validate_format 'ip'
is_ip_valid "$ip"
is_ip_key_empty '$U_WEB_DOMAINS'
is_ip_key_empty '$U_SYS_USERS'


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

# Defining config paths
conf='/etc/httpd/conf.d/vesta.conf'
nconf='/etc/nginx/conf.d/vesta_ip.conf'
iconf='/etc/sysconfig/network-scripts/ifcfg'
rconf='/etc/httpd/conf.d/rpaf.conf'

# Get ip owner
user="$(get_ip_value '$OWNER')"
ip_status="$(get_ip_value '$STATUS')"

# Deleting interface
get_current_interface
/sbin/ifconfig "$interface" down

# Deleting startup script
rm -f $iconf-$interface

# Deleting vesta ip
rm -f $VESTA/data/ips/$ip

# Deleting namehosting support
namehost_ip_disable


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

# Updating user conf
if [ ! -z "$user" ]; then
    decrease_user_value "$user" '$IP_OWNED'
fi

if [ "$user" = 'admin' ]; then
    if [ "$ip_status" = 'shared' ]; then
        for user in $(ls $VESTA/data/users/); do
            decrease_user_value "$user" '$IP_AVAIL'
        done
    else
        decrease_user_value 'admin' '$IP_AVAIL'
    fi
else
    decrease_user_value "$user" '$IP_AVAIL'
    decrease_user_value 'admin' '$IP_AVAIL'
fi


# Adding task to the vesta pipe
if [ "$web_restart" = 'yes' ]; then
    $BIN/v_restart_web "$EVENT"
fi

# Logging
log_event "$OK" "$EVENT"

exit
