#!/bin/bash
# info: change ip owner
# options: IP USER
#
# The function of changing ip address ownership.


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

# Argument definition
ip=$1
user=$2

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


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

check_args '2' "$#" 'IP USER'
is_format_valid 'ip' 'user'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_ip_valid "$ip"
is_ip_key_empty '$U_WEB_DOMAINS'
is_ip_key_empty '$U_SYS_USERS'

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

# Changing ip owner
ip_owner=$(get_ip_value '$OWNER')
if [ "$ip_owner" != "$user" ]; then
    ip_status="$(get_ip_value '$STATUS')"
    update_ip_value '$OWNER' "$user"
    decrease_user_value "$ip_owner" '$IP_OWNED'
    if [ "$ip_owner" = 'admin' ]; then
        if [ "$ip_status" = 'shared' ]; then
            for vesta_user in $(ls $VESTA/data/users); do
                decrease_user_value "$vesta_user" '$IP_AVAIL'
            done
        else
            decrease_user_value 'admin' '$IP_AVAIL'
        fi
    else
        decrease_user_value "$ip_owner" '$IP_AVAIL'
        decrease_user_value 'admin' '$IP_AVAIL'
    fi

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


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

# Logging
log_history "changed owner of $ip to $user" '' 'admin'
log_event "$OK" "$ARGUMENTS"

exit
