#!/bin/bash
# info: adding user package
# options: PKG_DIR PACKAGE [REWRITE]
#
# The function adds new user package to the system.


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

# Argument defenition
pkg_dir=$1
package=$2
rewrite=$3

# Includes
source $VESTA/func/main.sh
source $VESTA/conf/vesta.conf

# Functions
is_package_new() {
    if [ -e "$VESTA/data/packages/$package.pkg" ]; then
        echo "Error: package $package already exists."
        log_event "$E_EXISTS" "$EVENT"
        exit $E_EXISTS
    fi
}

is_package_consistent() {
    source $pkg_dir/$package.pkg
    validate_format_int $WEB_DOMAINS 'WEB_DOMAINS'
    validate_format_int $WEB_ALIASES 'WEB_ALIASES'
    validate_format_int $DNS_DOMAINS 'DNS_DOMAINS'
    validate_format_int $DNS_RECORDS 'DNS_RECORDS'
    validate_format_int $MAIL_DOMAINS 'MAIL_DOMAINS'
    validate_format_int $MAIL_ACCOUNTS 'MAIL_ACCOUNTS'
    validate_format_int $DATABASES 'DATABASES'
    validate_format_int $CRON_JOBS 'CRON_JOBS'
    validate_format_int $DISK_QUOTA 'DISK_QUOTA'
    validate_format_int $BACKUPS 'BACKUPS'
    validate_format_shell $SHELL
}


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

check_args '2' "$#" 'PKG_DIR PACKAGE' 'rewrite'
validate_format 'pkg_dir' 'package'
if [ "$rewrite" != 'yes' ]; then
    is_package_new
fi
is_package_valid "$pkg_dir"
is_package_consistent


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

cp -f $pkg_dir/$package.pkg $VESTA/data/packages/
chmod 644 $VESTA/data/packages/$package.pkg


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

# Logging
if [ "$rewrite" != 'yes' ]; then
    log_history "added user package $package" '' 'admin'
else
    log_history "updated user package $package" '' 'admin'
fi
log_event "$OK" "$EVENT"

exit
