#!/bin/bash
# info: change IP status
# options: IP IP_STATUS
#
# example: v-change-sys-ip-status 203.0.113.1 yourstatus
#
# This function of changing an IP address's status.

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

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

# Includes
# 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 IP_STATUS'
is_format_valid 'ip' 'ip_status'
is_ip_valid "$ip"
if [ "$ip_status" = "$(get_ip_value '$STATUS')" ]; then
	check_result "$E_EXISTS" "status $ip_status is already set"
fi
web_domains=$(get_ip_value '$U_WEB_DOMAINS')
sys_user=$(get_ip_value '$U_SYS_USERS')
ip_owner=$(get_ip_value '$OWNER')
if [ "$web_domains" -ne '0' ] && [ "$sys_user" != "$ip_owner" ]; then
	check_result "$E_INUSE" "IP $ip is used"
fi
if [ "$ip_owner" != "admin" ] && [ "$ip_status" = "shared" ]; then
	$BIN/v-change-sys-ip-owner "$ip" "admin"
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Changing IP status
update_ip_value '$STATUS' "$ip_status"

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

# Logging
$BIN/v-log-action "system" "Info" "System" "IP address status changed (Status: $ip_status, IP: $ip)."
log_event "$OK" "$ARGUMENTS"

exit
