#!/bin/bash
# info: change database server password
# options: TYPE HOST USER PASSWORD
#
# The function changes database server password.


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

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

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/db.sh
source $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/admin/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
log_event "$OK" "$ARGUMENTS"

exit
