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


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

# Argument definition
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" "$ARGUMENTS"
        exit $E_EXISTS
    fi
}

is_package_consistent() {
    source $pkg_dir/$package.pkg
    if [ "$WEB_DOMAINS" != 'unlimited' ]; then
        is_int_format_valid $WEB_DOMAINS 'WEB_DOMAINS'
    fi
    if [ "$WEB_ALIASES" != 'unlimited' ]; then
        is_int_format_valid $WEB_ALIASES 'WEB_ALIASES'
    fi
    if [ "$DNS_DOMAINS" != 'unlimited' ]; then
        is_int_format_valid $DNS_DOMAINS 'DNS_DOMAINS'
    fi
    if [ "$DNS_RECORDS" != 'unlimited' ]; then
        is_int_format_valid $DNS_RECORDS 'DNS_RECORDS'
    fi
    if [ "$MAIL_DOMAINS" != 'unlimited' ]; then
        is_int_format_valid $MAIL_DOMAINS 'MAIL_DOMAINS'
    fi
    if [ "$MAIL_ACCOUNTS" != 'unlimited' ]; then
        is_int_format_valid $MAIL_ACCOUNTS 'MAIL_ACCOUNTS'
    fi
    if [ "$DATABASES" != 'unlimited' ]; then
        is_int_format_valid $DATABASES 'DATABASES'
    fi
    if [ "$CRON_JOBS" != 'unlimited' ]; then
        is_int_format_valid $CRON_JOBS 'CRON_JOBS'
    fi
    if [ "$DISK_QUOTA" != 'unlimited' ]; then
        is_int_format_valid $DISK_QUOTA 'DISK_QUOTA'
    fi
    if [ "$BANDWIDTH" != 'unlimited' ]; then
        is_int_format_valid $BANDWIDTH 'BANDWIDTH'
    fi
    if [ "$BACKUPS" != 'unlimited' ]; then
        is_int_format_valid $BACKUPS 'BACKUPS'
    fi
    is_format_valid_shell $SHELL
}


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

check_args '2' "$#" 'PKG_DIR PACKAGE' 'rewrite'
is_format_valid '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" "$ARGUMENTS"

exit
