#!/bin/bash
# info: archive directory
# options: USER ARCHIVE SOURCE [SOURCE...]
#
# example: v-add-fs-archive admin archive.tar readme.txt
#
# This function creates tar archive

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

user=$1
archive=$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

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

check_args '3' "$#" 'USER ARCHIVE FILE [FILE_2] [FILE_3] [FILE ...]'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

# Checking user homedir
homedir=$(grep "^$user:" /etc/passwd | cut -f 6 -d :)
if [ -z "$homedir" ]; then
	echo "Error: user home directory doesn't exist"
	exit 12
fi

# Checking archive
if [ -e "$archive" ]; then
	echo "Error: archive already exist $archive"
	exit 1
fi

# Checking source path
IFS=$'\n'
i=1
for src in $*; do
	if [ "$i" -gt 2 ]; then
		rpath=$(readlink -f "$src")
		if [ -z "$(echo $rpath | egrep "^/tmp|^$homedir")" ]; then
			echo "Error: invalid source path $src"
			exit 1
		fi
	fi
	((i++))
done

i=1
for src in $*; do
	if [ "$i" -gt 2 ]; then
		# Deleting leading home path
		src=$(echo "$src" | sed -e "s|/home/$user/||")

		# Creating tar.gz archive
		user_exec tar -rf "${archive/.gz/}" -C /home/$user $src > /dev/null 2>&1
		if [ "$?" -ne 0 ]; then
			echo "Error: archive $archive was not created"
			exit 3
		fi
	fi
	((i++))
done

# Checking gzip
if [[ "$archive" =~ \.gz$ ]]; then
	user_exec gzip "${archive/.gz/}" > /dev/null 2>&1
	if [ "$?" -ne 0 ]; then
		echo "Error: archive $archive was not gziped"
		exit 3
	fi
fi

exit