#!/bin/bash
# info: Dumps database contents in STDIN or file optional file can be compressed
# options: USER DATABASE [FILE] [COMPRESSION]
#
# example: v-dump-database user user_databse > test.sql
# example: v-dump-database user user_databse file gzip
# example: v-dump-database user user_databse file zstd
#
# Dumps database in STDIN or file (/backup/user.database.type.sql)
# For compression gzip or zstd is supported by default plain sql is used

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

# Argument definition
user=$1
database=$2
output=$3
compression=$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"

check_args '2' "$#" 'USER DATABASE [OUTPUT] [COMPRESSION]'
is_format_valid 'user' 'database'
is_system_enabled "$DB_SYSTEM" 'DB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Create timestamp in Y-M-D_h-m-s format
timestamp=$(date +'%G-%m-%d_%H-%M-%S')

# Check db existence
db_data=$(grep "DB='$database'" $HESTIA/data/users/$user/db.conf)
if [ -z "$db_data" ]; then
	echo "Error: database $database doesn't exist"
	log_event "$E_NOTEXIST" "$ARGUMENTS"
	exit "$E_NOTEXIST"
fi

parse_object_kv_list "$db_data"

# Creating temporary directory
tmpdir=$(mktemp -p $BACKUP -d "tmp.$database.XXXXXXXXXX")

# Dump database
dump="$tmpdir/$database.$TYPE.sql"
grants="$tmpdir/$database.$TYPE.$DBUSER"
case $TYPE in
	mysql) dump_mysql_database ;;
	pgsql) dump_pgsql_database ;;
esac

if [ "$compression" = 'zstd' ]; then
	extension="sql.zst"
	pzstd --rm $dump
	dump="$tmpdir/$database.$TYPE.sql.zst"
elif [ "$compression" = 'gzip' ]; then
	extension="sql.gz"
	gzip $dump
	dump="$tmpdir/$database.$TYPE.sql.gz"
else
	extension="sql"
fi

if [ "$output" = "file" ]; then
	cp $dump $BACKUP/${user}_${database}_${TYPE}_${timestamp}.${extension}
	# echo file location for use in the php
	echo "$BACKUP/${user}_${database}_${TYPE}_${timestamp}.${extension}"

	# cleanup
	echo "rm $BACKUP/${user}_${database}_${TYPE}_${timestamp}.${extension}" | at now + 1 hour > /dev/null 2>&1
else
	cat $dump
fi

rm -fr $tmpdir

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

# Logging
log_event "$OK" "$ARGUMENTS"

exit
