#!/bin/bash
# info: change package name
# options: OLD_NAME NEW_NAME
#
# The function changes the name of an existing package.


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument definition
old_name=$1
new_name=$2

# Includes
source $HESTIA/func/main.sh
source $HESTIA/func/domain.sh
source $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."
fi
if [ -z "$new_name" ]; then
    echo "ERROR: New package name not specified."
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
    echo "Successfully renamed $old_name to $new_name."

    # Update package for existing users
    for user in `ls $HESTIA/data/users/`; do
        OLD_PACKAGE=$(v-get-user-value $user PACKAGE)
        if [ "$old_name" = "$OLD_PACKAGE" ]; then
            echo "Updating package for user: $user..."
            v-change-user-package $user $new_name
        fi
    done
else
    echo "ERROR: Specified package not found."
fi


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

# Logging
log_history "renamed package $old_name to $new_name"
log_event "$OK" "$ARGUMENTS"

exit
