#!/bin/bash
# info: rebuild databases
# options: USER
#
# example: v-rebuild-databases admin
#
# This function for rebuilding of all databases of a single user.

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

# Argument definition
user=$1

# 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/db.sh
source $HESTIA/func/db.sh
# shellcheck source=/usr/local/hestia/func/rebuild.sh
source $HESTIA/func/rebuild.sh
# shellcheck source=/usr/local/hestia/func/syshealth.sh
source $HESTIA/func/syshealth.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '1' "$#" 'USER'
is_format_valid 'user'
is_system_enabled "$DB_SYSTEM" 'DB_SYSTEM'
is_object_valid 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Flush counters
U_DATABASES=0
SUSPENDED_DB=0
U_DISK_DB=0

# Starting rebuild loop
for database in $(search_objects 'db' 'SUSPENDED' "no" 'DB'); do

	# Get database values
	get_database_values

	# Switching on db type
	case $TYPE in
		mysql) rebuild_mysql_database ;;
		pgsql) rebuild_pgsql_database ;;
	esac

	U_DISK_DB=$((U_DISK_DB + U_DISK))
	U_DATABASES=$((U_DATABASES + 1))
	if [ "$SUSPENDED" = 'yes' ]; then
		SUSPENDED_DB=$((SUSPENDED_DB + 1))
	fi
done

update_user_value "$user" '$SUSPENDED_DB' "$SUSPENDED_DB"
update_user_value "$user" '$U_DATABASES' "$U_DATABASES"
update_user_value "$user" '$U_DISK_DB' "$U_DISK_DB"

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

# Logging
$BIN/v-log-action "system" "Info" "System" "Rebuilt databases (User: $user)."
log_event "$OK" "$ARGUMENTS"

exit