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


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument definition
user=$1
database=$2

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/db.sh
source $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_unsuspended 'user' 'USER' "$user"
is_object_valid 'db' 'DB' "$database"
is_object_unsuspended 'db' 'DB' "$database"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

# Get database values
get_database_values

# 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'

# Logging
log_history "deleted $database database"
log_event "$OK" "$ARGUMENTS"

exit
