#!/bin/bash
# info: delete database
# options: USER DATABASE
#
# example: v-delete-database admin wp_db
#
# This function for deleting the database. If database user have access to
# another database, he will not be deleted.

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

# Argument definition
user=$1
database=$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/db.sh
source $HESTIA/func/db.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

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

check_args '2' "$#" 'USER DATABASE'
is_format_valid 'user' 'database'
is_system_enabled "$DB_SYSTEM" 'DB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'db' 'DB' "$database"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Get database values
get_database_values
# Issues with $SUSPENDED overwritten when delete_mysql_database is called
suspended=$SUSPENDED

# Switching on db type
case $TYPE in
	mysql) delete_mysql_database ;;
	pgsql) delete_pgsql_database ;;
esac

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

# Deleting database
sed -i "/DB='$database' /d" $USER_DATA/db.conf

# Decreasing counters
decrease_dbhost_values
decrease_user_value "$user" '$U_DATABASES'

# Check if is suspended to decrease the suspended value
if [ -n "$suspended" ]; then
	if [ "$suspended" == "yes" ]; then
		decrease_user_value "$user" '$SUSPENDED_DB'
	fi
fi

# Logging
$BIN/v-log-action "$user" "Info" "Database" "Deleted database (Name: $database)."
log_event "$OK" "$ARGUMENTS"

exit
