#!/bin/bash
# info: add temp database user
# options: USER DATABASE [TYPE] [HOST] [TTL]
#
# example: v-add-database-temp-user wordress wordpress_db mysql
#
# This function creates an temporary database user mysql_sso_db_XXXXXXXX and a random password
# The user has an limited validity and only granted access to the specific database
# Returns json to be read SSO Script

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

# Argument definition
user=$1
database="$2"
type=${3-mysql}
host=$4
ttl=$5

if [ "$ttl" == '' ]; then
	ttl=60
fi

# 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 [TYPE] [HOST] [TTL]'
is_format_valid 'user' 'database' 'ttl'
is_type_valid "$DB_SYSTEM" "$type"
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"
get_next_dbhost

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Get database values
get_database_values

#generate password and unique user
dbpass=$(generate_password)
dbuser="hestia_sso_$(generate_password)"

add_mysql_database_temp_user
if [ $? -ne 0 ]; then
	echo "Error: Unable to create temp user"
	exit 2
fi

if [[ "$ttl" -gt 0 ]]; then
	echo "$BIN/v-delete-database-temp-user $user $database $dbuser mysql $host" | at "now +${ttl} minute" > /dev/null 2>&1
fi
echo '{
    "login": {
        "user": "'$dbuser'",
        "password": "'$dbpass'"
    }
}'

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

# Logging
$BIN/v-log-action "$user" "Info" "Databases" "Granted user $dbuser access to database $database."
log_event "$OK" "$ARGUMENTS"
exit