#!/bin/bash
# info: change IP owner
# options: IP USER
#
# example: v-change-sys-ip-owner 203.0.113.1 admin
#
# This function of changing IP address ownership.

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

# Argument definition
ip="$1"
user="$2"

# shellcheck source=/etc/hestiacp/hestia.conf
source /etc/hestiacp/hestia.conf
# shellcheck source=/usr/local/hestia/func/main.sh
source $HESTIA/func/main.sh
# shellcheck source=/usr/local/hestia/func/ip.sh
source $HESTIA/func/ip.sh
# load config file
source_conf "$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 $($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 $($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
	$BIN/v-change-sys-ip-status "$ip" 'dedicated'
fi

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

# Logging
$BIN/v-log-action "system" "Info" "System" "IP address owner changed (IP: $ip, Owner: $user)"
log_event "$OK" "$ARGUMENTS"

exit