#!/bin/bash
# info: restore WEB domain
# options: USER SNAPSHOT DOMAIN
#
# example: v-restore-web-domain-restic user snapshot domain.com
# example: v-restore-web-domain-restic user snapshot 'domain.com,domain2.com'
# example: v-restore-web-domain-restic user snapsho '*'
#
# This function for restoring database from restic snapshot.

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

# Argument definition
user=$1
snapshot=$2
web=$3
notify=${4-no}
new_user=${5-no}

# 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/domain.sh
source $HESTIA/func/domain.sh
# shellcheck source=/usr/local/hestia/func/ip.sh
source $HESTIA/func/ip.sh
# shellcheck source=/usr/local/hestia/func/rebuild.sh
source $HESTIA/func/rebuild.sh
# shellcheck source=/usr/local/hestia/func/syshealth.sh
source $HESTIA/func/syshealth.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

source_conf $HESTIA/conf/restic.conf

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

args_usage='USER SNAPSHOT DOMAIN [NOTIFY] [NEW_USER]'
check_args '3' "$#" "$args_usage"
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"

source_conf $HESTIA/conf/restic.conf

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

tmpdir=$(mktemp -p /home/$user/tmp/ -d)
if [ ! -f "$tmpdir/backup.conf" ]; then
	restic --repo "$REPO$user" --password-file "$USER_DATA/restic.conf" dump "$snapshot" "/home/$user/backup/backup.conf" > "$tmpdir/backup.conf"
	if [ "$?" -ne 0 ]; then
		check_result "$E_NOTEXIST" "Unable to download from snapshot"
	fi
fi
restic --repo "$REPO$user" --password-file "$USER_DATA/restic.conf" dump "$snapshot" "/home/$user/backup/pam/passwd" > "$tmpdir/passwd"
old_uid=$(cut -f 3 -d : $tmpdir/passwd)

domains=""
parse_object_kv_list $(cat $tmpdir/backup.conf)
IFS=','
read -a domains_array <<< "$web"
read -a domains <<< "$WEB"
for domain in $domains; do
	if [[ "${IFS}${domains_array[*]}${IFS}" =~ "${IFS}${domain}${IFS}" || "$web" = '*' ]]; then
		# Cleanup previous domain keys
		unset -v DOMAIN IP IP6 ALIAS TPL SSL SSL_HOME LETSENCRYPT FTP_USER FTP_MD5 BACKEND PROXY PROXY_EXT STATS STATS_USER STATS_CRYPT U_DISK CUSTOM_DOCROOT CUSTOM_PHPROOT

		# Checking domain existence
		check_config=$(grep "DOMAIN='$domain'" $USER_DATA/web.conf)
		if [ -z "$check_config" ]; then
			check_new=$(is_domain_new 'web' $domain)
			if [ "$check_new" = 'yes' ]; then
				rm -rf $tmpdir
				error="$domain belongs to another user"
				echo "$error" | $SENDMAIL -s "$subj" $email $notify
				sed -i "/ $user /d" $HESTIA/data/queue/backup.pipe
				check_result "$E_PARSING" "$error"
			fi
		fi
		restic --repo "$REPO$user" --password-file "$USER_DATA/restic.conf" restore "$snapshot" --include "/home/$user/backup/web/$domain" --target "$tmpdir"
		if [ "$?" -ne 0 ]; then
			check_result $E_NOTEXIST "Unable to download domain from snapshot"
		fi

		# Restoring web.conf
		if [ -z "$check_config" ]; then
			parse_object_kv_list $(cat $tmpdir/home/$user/backup/web/$domain/hestia/web.conf)

			# Deleting conflicting aliases
			for dom_alias in ${ALIAS//,/ }; do
				check_new=$(is_domain_new 'web' $dom_alias)
				if [ -n "$check_new" ]; then
					ALIAS=$(echo "$ALIAS" \
						| sed "s/,/\n/g" \
						| sed "s/^$dom_alias$//g" \
						| sed "/^$/d" \
						| sed ':a;N;$!ba;s/\n/,/g')
				fi
			done

			# Checking IP address
			check_ip=$(is_ip_valid $IP $user)
			if [ -n "$check_ip" ]; then
				local_ip=''
				get_user_ip $user
				old_ip=$IP
				IP=$ip
			fi

			# Checking web template
			check_tpl=$(is_web_template_valid $TPL)
			if [ -n "$check_tpl" ]; then
				TPL='default'
			fi

			# Checking proxy template
			check_proxy_tpl=$(is_proxy_template_valid $PROXY)
			if [ -n "$check_proxy_tpl" ]; then
				PROXY='default'
			fi

			# Checking backend template
			check_backend_tpl=$(is_backend_template_valid $BACKEND)
			if [ -n "$check_backend_tpl" ]; then
				BACKEND='default'
			fi

			if [ -n "$CUSTOM_DOCROOT" ]; then
				CUSTOM_DOCROOT=$(echo "$CUSTOM_DOCROOT" | sed -e "s|/home/${old_user}/web/|/home/${user}/web/")
			fi
			if [ -n "$CUSTOM_PHPROOT" ]; then
				CUSTOM_PHPROOT=$(echo "$CUSTOM_PHPROOT" | sed -e "s|/home/${old_user}/web/|/home/${user}/web/")
			fi

			# Converting FTP users
			if [ -n "$FTP_USER" ]; then
				FTP_USER=$(echo "$FTP_USER" | sed -e "s/${old_user}_//")
				FTP_USER="${user}_${FTP_USER}"
			fi
			# Copying SSL certificates
			if [ "$SSL" = 'yes' ]; then

				if [ -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.crt" ]; then
					cp -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.crt" "$USER_DATA/ssl/"
					if [ -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.ca" ]; then
						cp -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.ca" "$USER_DATA/ssl/"
					fi
					if [ -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.pem" ]; then
						cp -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.pem" "$USER_DATA/ssl/"
					fi
					if [ -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.key" ]; then
						cp -f "$tmpdir/home/$user/backup/web/$domain/hestia/$domain.key" "$USER_DATA/ssl/"
					fi
				fi
			fi

			# Merging web.conf keys
			str="DOMAIN='$domain' IP='$IP' IP6='$IP6' ALIAS='$ALIAS'"
			str="$str CUSTOM_DOCROOT='$CUSTOM_DOCROOT' CUSTOM_PHPROOT='$CUSTOM_PHPROOT'"
			str="$str REDIRECT='$REDIRECT' REDIRECT_CODE='$REDIRECT_CODE'"
			str="$str FASTCGI_CACHE='$FASTCGI_CACHE' FASTCGI_DURATION='$FASTCGI_DURATION'"
			str="$str TPL='$TPL' SSL='$SSL' SSL_HOME='$SSL_HOME' SSL_HSTS='$SSL_HSTS'"
			str="$str SSL_FORCE='$SSL_FORCE' LETSENCRYPT='$LETSENCRYPT' FTP_USER='$FTP_USER'"
			str="$str FTP_MD5='$FTP_MD5' FTP_PATH='$FTP_PATH'"
			str="$str BACKEND='$BACKEND' PROXY='$PROXY'"
			str="$str PROXY_EXT='$PROXY_EXT' STATS='$STATS'"
			str="$str STATS_USER='$STATS_USER' STATS_CRYPT='$STATS_CRYPT'"
			str="$str U_DISK='$U_DISK' U_BANDWIDTH='0' SUSPENDED='no'"
			str="$str TIME='$(date +%T)' DATE='$(date +%F)'"
			echo $str >> $USER_DATA/web.conf

			# Rebuilding backend
			if [ -n "$WEB_BACKEND" ]; then
				$BIN/v-add-web-domain-backend $user $domain $BACKEND
			fi

			# Restoring custom user config
			# Except certificates, .conf files
		fi

		if [ ! -d "$HOMEDIR/$user/conf/web/$domain/" ]; then
			mkdir -p $HOMEDIR/$user/conf/web/$domain/
		fi
		for file in $tmpdir/home/$user/backup/web/$domain/conf/*; do
			if [[ "$file" == *.ca ]] || [[ "$file" == *.crt ]] || [[ "$file" == *.key ]] || [[ "$file" == *.pem ]] || [[ "$file" == *.conf ]]; then
				continue
			fi
			if grep "fastcgi_pass" "$file"; then
				# Do not allow to run php under a different user
				continue
			fi
			filename=$(basename "$file")
			cp -f "$file" "$HOMEDIR/$user/conf/web/$domain/$filename"
		done

		# Rebuilding vhost to prevent user overwrite default config changes not ideal
		rebuild_web_domain_conf

		if [ -d "$HOMEDIR/$user/web/$domain/public_html" ]; then
			rm -rf $HOMEDIR/$user/web/$domain/public_html/*
		fi

		[[ -d $HOMEDIR/$user/web/$domain/stats ]] && chmod u+w "$HOMEDIR/$user/web/$domain/stats"

		restic --repo "$REPO$user" --password-file "$USER_DATA/restic.conf" restore "$snapshot" --include "/home/$user/web/$domain" --target /
		if [ "$?" -ne 0 ]; then
			check_result "$E_NOTEXIST" "Unable to download user data"
		fi
		if [ "$new_user" = "yes" ]; then
			echo "[ * ] Fix permissions"
			chown --no-dereference $user:$user \
				$HOMEDIR/$user/ \
				$HOMEDIR/$user/web/ \
				$HOMEDIR/$user/web/$domain \
				$HOMEDIR/$user/web/$domain/private \
				$HOMEDIR/$user/web/$domain/cgi-bin \
				$HOMEDIR/$user/web/$domain/public_*html \
				$HOMEDIR/$user/web/$domain/logs \
				$HOMEDIR/$user/web/$domain/stats

			chown -R $user:$user $HOMEDIR/$user/web/$domain/document_errors
			chown root:$user /var/log/$WEB_SYSTEM/domains/$domain.*
		fi
		# Rebuilding web config for the second time to make sure ftp users keep working
		rebuild_web_domain_conf

	fi
done
#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#
if [ "$new_user" = "yes" ]; then
	rebuild_user_conf
fi
rm -fr $tmpdir

# Update user counters
$BIN/v-update-user-counters $user
$BIN/v-update-user-counters admin
$BIN/v-update-sys-ip-counters

sed -i "/v-restore-web-domain-restic '$user' '$snapshot' '$web' /d" $HESTIA/data/queue/backup.pipe

# Logging
$BIN/v-log-action "system" "Info" "Backup" "Web domain successfully restored (User: $user, Snapshot: $snapshot, Databse: $database)."
$BIN/v-log-action "$user" "Info" "Backup" "Web domain successfully restored (User: $user, Snapshot: $snapshot, Databse: $database)."
log_event "$OK" "$ARGUMENTS"
exit
