#!/bin/bash
# info: change database password
# options: USER DATABASE DBPASS
#
# example: v-change-database-password admin wp_db neW_pAssWorD
#
# This function for changing database user password to a database. It uses the
# full name of database as argument.

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

# Argument definition
user=$1
database=$2
password=$3
HIDE=3

# 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 '3' "$#" 'USER DATABASE DBPASS'
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"
is_password_valid
dbpass="$password"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#
# Get database values
get_database_values

case $TYPE in
	mysql) change_mysql_password ;;
	pgsql) change_pgsql_password ;;
esac

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

# Update config value
update_object_value 'db' 'DB' "$database" '$MD5' "$md5"

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

exit
