#!/bin/bash
# info: change database server password
# options: TYPE HOST USER PASSWORD
#
# example: v-change-database-host-password mysql localhost wp_user pA$$w@rD
#
# This function changes database server password.

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

# Argument definition
type=$1
host=$2
dbuser=$3
password=$4
HIDE=4

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

args_usage='TYPE HOST DBUSER DBPASS'
check_args '4' "$#" "$args_usage"
is_format_valid 'host' 'dbuser'
is_object_valid "../../conf/$type" 'HOST' "$host"
dbpass="$password"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Define email
email=$(grep CONTACT "$HESTIA/data/users/$ROOT_USER/user.conf" | cut -f2 -d \')
subj="v-change-database-host-password $*"

case $type in
	mysql)
		mysql_connect "$host"
		query="USE mysql; UPDATE user SET"
		query="$query password=PASSWORD('$dbpass')"
		query="$query WHERE User='$dbuser';"
		query="$query FLUSH PRIVILEGES;"
		mysql_query "$query"
		if [ "$dbuser" == "root" ]; then
			echo -e "[client]\npassword='$dbpass'\n" > /root/.my.cnf
			chmod 600 /root/.my.cnf
		fi
		;;
	pgsql) echo "TBD" > /dev/null ;;
esac

update_object_value "../../conf/$type" 'HOST' "$host" '$USER' "$dbuser"
update_object_value "../../conf/$type" 'HOST' "$host" '$PASSWORD' "$dbpass"

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

# Logging
$BIN/v-log-action "system" "Warning" "Database" "Password changed for remote database host (Host: $host)."
log_event "$OK" "$ARGUMENTS"

exit
