#!/bin/bash
# info: Allow other users create subdomains
# options: USER DOMAIN
#
# example: v-add-web-domain-allow-users admin admin.com
#
# Bypass the rule check for Enforce subdomain ownership for a specific domain.
# Enforce subdomain ownership setting in /edit/server/ set to no will always overwrite this behaviour
# eg: admin adds admin.com
# user can create user.admin.com

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

# Argument definition
user=$1
domain=$2
domain_idn=$2

# 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
# shellcheck source=/usr/local/hestia/func/ip.sh
source $HESTIA/func/ip.sh
# load config file
source_conf "$HESTIA/conf/hestia.conf"

# Additional argument formatting
format_domain

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

check_args '2' "$#" 'USER DOMAIN'
is_format_valid 'user' 'domain'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Load domain data
parse_object_kv_list $(grep "DOMAIN='$domain'" $USER_DATA/web.conf)

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

if [ -z "$ALLOW_USERS" ]; then
	add_object_key "web" 'DOMAIN' "$domain" 'ALLOW_USERS' 'TIME'
fi

# Adding new alias
update_object_value 'web' 'DOMAIN' "$domain" '$ALLOW_USERS' "yes"

$BIN/v-log-action "$user" "Warning" "Web" "Subdomain ownership enforcement disabled (Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit
