#!/bin/bash
# info: activate vesta license
# options: MODULE LICENSE
#
# The function activates and registers the vesta license


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

# Argument definition
module=$(echo $1 | tr '[:lower:]' '[:upper:]')
license=$2

# Importing system environment
source /etc/profile

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


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

# Checking arg number
check_args '2' "$#" 'MODULE LICENSE'
is_user_format_valid "$license" "license"

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

# Activating license
v_host='https://vestacp.com/checkout'
answer=$(curl -s "$v_host/activate.php?licence_key=$license&module=$module")
check_result $? "cant' connect to vestacp.com " $E_CONNECT

# Checking server answer
if [[ "$answer" != '0' ]]; then
    echo "Error: $module license $license is invalid"
    exit $E_INVALID
fi


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

# Updating vesta.conf
if [ -z "$(grep "${module}_KEY" $VESTA/conf/vesta.conf)" ]; then
    echo "${module}_KEY='$license'" >> $VESTA/conf/vesta.conf
else
    sed -i "s/${module}_KEY=.*/${module}_KEY='$license'/g" $VESTA/conf/vesta.conf
fi

# Activating sftpjail
if [ "$module" = 'SFTPJAIL' ]; then
    setsid $BIN/v-add-sys-sftp-jail 2>/dev/null
fi

# Logging
log_event "$OK" "$ARGUMENTS"

exit
