#!/bin/bash
# info: change package name
# options: OLD_NAME NEW_NAME [mode]
#
# example: v-rename-package package package2
#
# This function changes the name of an existing package.

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

# Argument definition
old_name=$1
new_name=$2
mode=$3

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

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

# Ensure that package names have been passed to the script.
if [ -z "$old_name" ]; then
	echo "ERROR: Current package name not specified."
	exit "$E_ARGS"
fi
if [ -z "$new_name" ]; then
	echo "ERROR: New package name not specified."
	exit "$E_ARGS"
fi

is_package_valid "$old_name"
is_object_format_valid "$new_name" "New package"
pkg_dir="$HESTIA/data/packages"
if [ -e "$pkg_dir/$new_name.pkg" ]; then
	check_result "$E_NOTEXIST" "package $new_name exist"
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

if [ -e "$HESTIA/data/packages/$old_name.pkg" ]; then
	mv "$HESTIA/data/packages/$old_name.pkg" "$HESTIA/data/packages/$new_name.pkg"
	# Don't leave the .sh file behind
	if [ -e "$HESTIA/data/packages/$old_name.sh" ]; then
		mv "$HESTIA/data/packages/$old_name.sh" "$HESTIA/data/packages/$new_name.sh"
	fi

	# Update package for existing users
	for user in $($BIN/v-list-users plain); do
		OLD_PACKAGE=$(v-get-user-value "$user" 'PACKAGE')
		if [ "$old_name" = "$OLD_PACKAGE" ]; then
			if [ "$mode" == "yes" ]; then
				echo "Successfully renamed package $old_name to $new_name."
			fi
			v-change-user-package "$user" "$new_name"
		fi
	done
	if [ "$mode" == "yes" ]; then
		echo "Successfully renamed package $old_name to $new_name."
	fi
else
	echo "ERROR: Specified package not found."
	exit "$E_NOTEXIST"
fi

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

# Logging
$BIN/v-log-action "system" "Info" "System" "Package renamed (Value: $new_name, Previous: $old_name)."
log_event "$OK" "$ARGUMENTS"

exit