#!/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 $HESTIA/func/ip.sh
source $HESTIA/func/main.sh
source $HESTIA/conf/hestia.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'

ip_status="$(get_ip_value '$STATUS')"


# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

# Changing ip owner
ip_owner=$(get_ip_value '$OWNER')
if [ "$ip_owner" != "$user" ]; then
    update_ip_value '$OWNER' "$user"
    decrease_user_value "$ip_owner" '$IP_OWNED'
    if [ "$ip_owner" = 'admin' ]; then
        if [ "$ip_status" = 'shared' ]; then
            for hestia_user in $($HESTIA/bin/v-list-sys-users plain); do
                decrease_user_value "$hestia_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 hestia_user in $($HESTIA/bin/v-list-sys-users plain); do
                increase_user_value "$hestia_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

# Set status to dedicated if owner is not admin
ip_status="$(get_ip_value '$STATUS')"
if [ "$user" != 'admin' ] && [ "$ip_status" == 'shared' ]; then
    $HESTIA/bin/v-change-sys-ip-status "$ip" 'dedicated'
fi

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

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

exit
