#!/bin/bash
# info: update backup exclusion list
# options: USER FILE
#
# example: v-update-user-backup-exclusions admin /tmp/backup_exclusions
#
# This function for updating backup exclusion list

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

# Argument definition
user=$1
vfile=$2

# 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
# load config file
source_conf "$HESTIA/conf/hestia.conf"

is_file_available() {
	if [ ! -e "$vfile" ]; then
		check_result "$E_NOTEXIST" "file $vfile doesn't exist"
	fi
}

is_file_valid() {
	exclude="[!|#|$|^|&|(|)|{|}|<|>|?|\|\"|;|%|\`]"
	if [[ "$(cat $vfile)" =~ $exclude ]]; then
		check_result "$E_INVALID" "invalid characters in the exlusion list"
	fi
}

#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '2' "$#" 'USER FILE'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"
is_file_available
is_file_valid

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Flush variables
WEB=''
DNS=''
MAIL=''
DB=''
CRON=''
USER=''

# Source exclusion list
source_conf "$vfile"

# Updating exlusion list
echo "WEB='$WEB'" > $USER_DATA/backup-excludes.conf
echo "DNS='$DNS'" >> $USER_DATA/backup-excludes.conf
echo "MAIL='$MAIL'" >> $USER_DATA/backup-excludes.conf
echo "DB='$DB'" >> $USER_DATA/backup-excludes.conf
echo "CRON='$CRON'" >> $USER_DATA/backup-excludes.conf
echo "USER='$USER'" >> $USER_DATA/backup-excludes.conf
chmod 660 $USER_DATA/backup-excludes.conf

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

# Logging
$BIN/v-log-action "$user" "Info" "Backups" "Updated backup exclusion list."
log_event "$OK" "$ARGUMENTS"

exit
