#!/bin/bash
# info: duplicate existing package
# options: PACKAGE NEW_PACKAGE
#
# example: v-copy-user-package default new
#
# This function allows the user to duplicate an existing
# package file to facilitate easier configuration.

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

# Argument definition
package=$1
new_package=$2

# Includes
# shellcheck source=/etc/tuliocp/tulio.conf
source /etc/tuliocp/tulio.conf
# shellcheck source=/usr/local/tulio/func/main.sh
source $TULIO/func/main.sh
# shellcheck source=/usr/local/tulio/conf/tulio.conf
source $TULIO/conf/tulio.conf
# load config file
source_conf "$TULIO/conf/tulio.conf"

# Perform verification if read-only mode is enabled
check_tulio_demo_mode

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

is_package_valid "$package"
is_package_new "$new_package"
is_object_format_valid "$package" "Package"
is_object_format_valid "$new_package" "New package"

if [ -n "$1" ]; then
	if [ ! -f "$TULIO/data/packages/$package.pkg" ]; then
		echo "Error: package does not exist."
		exit "$E_NOTEXIST"
	fi
	if [ -n "$2" ]; then
		# Copy package
		cp -f "$TULIO/data/packages/$package.pkg" "$TULIO/data/packages/$new_package.pkg"
		# Don't leave the .sh file behind
		if [ -f "$TULIO/data/packages/$package.sh" ]; then
			cp $TULIO/data/packages/$package.sh $TULIO/data/packages/$new_package.sh
		fi
	else
		echo "Error: new package name not specified."
		exit "$E_ARGS"
	fi
else
	echo "Error: package name not specified."
	exit "$E_ARGS"
fi

#----------------------------------------------------------#
#                       Tulio                             #
#----------------------------------------------------------#

$BIN/v-log-action "system" "Info" "System" "Package copied (Package: $package, New Package: $new_package)."
log_event "$OK" "$ARGUMENTS"

exit
