#!/bin/bash
# info: add web domain
# options: USER DOMAIN [IP] [RESTART] [ALIASES] [PROXY_EXTENSIONS]
#
# example: v-add-web-domain admin wonderland.com 192.18.22.43 yes www.wonderland.com
#
# This function adds virtual host to a server. In cases when ip is
# undefined in the script, "default" template will be used. The alias of
# www.domain.tld type will be automatically assigned to the domain unless
# "none" is transmited as argument. If ip have associated dns name, this
# domain will also get the alias domain-tpl.$ipname. An alias with the ip
# name is useful during the site testing while dns isn't moved to server yet.

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

# Argument definition
user=$1
domain=$2
domain_idn=$2
ip=$3
restart=$4 # will be moved to the end soon
aliases=$5
proxy_ext=$6

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

# Additional argument formatting
format_domain
format_domain_idn
format_aliases
domain_utf=$(idn2 --quiet -d "$domain_idn")


WWW_USER="www-data"
if [ -f /etc/redhat-release ]; then
    WWW_USER="apache"
fi

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

is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
check_args '2' "$#" 'USER DOMAIN [IP] [RESTART] [ALIASES] [PROXY_EXTENSIONS]'
is_format_valid 'user' 'domain' 'aliases' 'ip' 'proxy_ext'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_package_full 'WEB_DOMAINS'

if [ "$aliases" != "none" ]; then
	ALIAS="$aliases"
	is_package_full 'WEB_ALIASES'
fi

if [ "$($BIN/v-list-web-domain $user $domain_utf plain | cut -f 1) " != "$domain" ]; then
	is_domain_new 'web' "$domain_utf,$aliases"
fi
if [ "$($BIN/v-list-web-domain $user $domain_idn plain | cut -f 1) " != "$domain" ]; then
	is_domain_new 'web' "$domain_idn,$aliases"
else
	is_domain_new 'web' "$domain,$aliases"
fi
if [ -z "$(is_ip_format_valid $domain)" ]; then
	echo "Error: Invalid domain format. IP address detected as input."
	exit 1
fi

is_dir_symlink "$HOMEDIR/$user/web"
is_dir_symlink "$HOMEDIR/$user/web/$domain"

is_base_domain_owner "$domain,$aliases"

if [ -n "$ip" ]; then
	is_ip_valid "$ip" "$user"
else
	get_user_ip
fi

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Reading user values
source_conf "$USER_DATA/user.conf"

[[ -e "$HOMEDIR/$user/web/$domain" ]] && check_result "$E_EXISTS" "Web domain folder for $domain should not exist"

# Creating domain directories
mkdir $HOMEDIR/$user/web/$domain
chown $user:$user $HOMEDIR/$user/web/$domain
$BIN/v-add-fs-directory "$user" "$HOMEDIR/$user/web/$domain/public_html"
$BIN/v-add-fs-directory "$user" "$HOMEDIR/$user/web/$domain/document_errors"
$BIN/v-add-fs-directory "$user" "$HOMEDIR/$user/web/$domain/cgi-bin"
$BIN/v-add-fs-directory "$user" "$HOMEDIR/$user/web/$domain/private"
$BIN/v-add-fs-directory "$user" "$HOMEDIR/$user/web/$domain/stats"
$BIN/v-add-fs-directory "$user" "$HOMEDIR/$user/web/$domain/logs"
$BIN/v-add-fs-directory "$user" "$HOMEDIR/$user/web/$domain/private/tmp"

# Creating domain logs
touch /var/log/$WEB_SYSTEM/domains/$domain.bytes \
	/var/log/$WEB_SYSTEM/domains/$domain.log \
	/var/log/$WEB_SYSTEM/domains/$domain.error.log
ln -f -s /var/log/$WEB_SYSTEM/domains/$domain.*log \
	$HOMEDIR/$user/web/$domain/logs/

# Adding domain skeleton
user_exec cp -r $WEBTPL/skel/* "$HOMEDIR/$user/web/$domain/" > /dev/null 2>&1
for file in $(find "$HOMEDIR/$user/web/$domain/" -type f); do
	sed -i "s/%domain%/$domain/g" $file
done

# Changing file owner & permission
chown -R $user:$user $HOMEDIR/$user/web/$domain
chown root:$user /var/log/$WEB_SYSTEM/domains/$domain.* $conf
chmod 640 /var/log/$WEB_SYSTEM/domains/$domain.*
user_exec chmod 751 $HOMEDIR/$user/web/$domain/*
user_exec chmod 551 $HOMEDIR/$user/web/$domain/stats $HOMEDIR/$user/web/$domain/logs
user_exec chmod 644 $HOMEDIR/$user/web/$domain/public_*html/*
user_exec chmod 551 $HOMEDIR/$user/web/$domain
chown --no-dereference $user:$WWW_USER $HOMEDIR/$user/web/$domain/public_*html

# Adding PHP-FPM backend
if [ -n "$WEB_BACKEND" ]; then
	if [ -z "$BACKEND_TEMPLATE" ]; then
		BACKEND_TEMPLATE='default'
		if [ -z "$(grep BACKEND_TEMPLATE $USER_DATA/user.conf)" ]; then
			sed -i "s/^DNS_TEMPL/BACKEND_TEMPLATE='default'\nDNS_TEMPL/g" \
				$USER_DATA/user.conf
		else
			update_user_value "$user" '$BACKEND_TEMPLATE' "default"
		fi
	fi
	export BACKEND="$BACKEND_TEMPLATE"
	$BIN/v-add-web-domain-backend "$user" "$domain" "$BACKEND_TEMPLATE" "$restart"
	check_result $? "Backend error" > /dev/null
fi

# Preparing domain aliases
if [ "$aliases" = 'none' ]; then
	ALIAS=''
else
	ALIAS="www.$domain"
	if [ -z "$aliases" ]; then
		# Check and skip www alias for subdomains.
		IFS='.' read -r -a domain_elements <<< "$domain"
		if [ "${#domain_elements[@]}" -gt 2 ]; then
			is_valid_2_part_extension $domain
			if [ $? -ne 0 ]; then
				ALIAS=""
			else
				ALIAS="www.$domain"
			fi
		else
			ALIAS="www.$domain"
		fi
	else
		ALIAS="$aliases"
	fi

	ip_alias=$(get_ip_alias "$domain")
	if [ -n "$ip_alias" ]; then
		ALIAS="$ALIAS,$ip_alias"
	fi
fi

# Preparing domain variables
prepare_web_domain_values

if [ -z "$WEB_TEMPLATE" ]; then
	WEB_TEMPLATE='default'
	update_user_value "$user" '$WEB_TEMPLATE' "default"
fi

# Adding web server config
add_web_config "$WEB_SYSTEM" "$WEB_TEMPLATE.tpl"

# Adding proxy config
if [ -n "$PROXY_SYSTEM" ]; then
	PROXY_EXT="$proxy_ext"
	if [ -z "$proxy_ext" ]; then
		# Code
		PROXY_EXT="css,htm,html,js,json,xml"
		# Image (from https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types)
		PROXY_EXT="$PROXY_EXT,apng,avif,bmp,cur,gif,ico,jfif,jpg,jpeg,pjp,pjpeg,png,svg,tif,tiff,webp"
		# Audio from (https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_codecs)
		PROXY_EXT="$PROXY_EXT,aac,caf,flac,m4a,midi,mp3,ogg,opus,wav"
		# Video (from https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_codecs)
		PROXY_EXT="$PROXY_EXT,3gp,av1,avi,m4v,mkv,mov,mpg,mpeg,mp4,mp4v,webm"
		# Fonts
		PROXY_EXT="$PROXY_EXT,otf,ttf,woff,woff2"
		# Productivity
		PROXY_EXT="$PROXY_EXT,doc,docx,odf,odp,ods,odt,pdf,ppt,pptx,rtf,txt,xls,xlsx"
		# Archive
		PROXY_EXT="$PROXY_EXT,7z,bz2,gz,rar,tar,tgz,zip"
		# Binaries
		PROXY_EXT="$PROXY_EXT,apk,appx,bin,dmg,exe,img,iso,jar,msi"
	fi
	if [ -z "$PROXY_TEMPLATE" ]; then
		PROXY_TEMPLATE='default'
		update_user_value "$user" '$PROXY_TEMPLATE' "default"
	fi

	add_web_config "$PROXY_SYSTEM" "$PROXY_TEMPLATE.tpl"
fi

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

# Increasing counters
increase_ip_value "$local_ip"
increase_user_value "$user" '$U_WEB_DOMAINS'
increase_user_value "$user" '$U_WEB_ALIASES' "$alias_number"

# Generating timestamp
time_n_date=$(date +'%T %F')
time=$(echo "$time_n_date" | cut -f 1 -d \ )
date=$(echo "$time_n_date" | cut -f 2 -d \ )

# Adding domain in web.conf
echo "DOMAIN='$domain' IP='$ip' IP6='' CUSTOM_DOCROOT='' ALIAS='$ALIAS' TPL='$WEB_TEMPLATE'\
 SSL='no' SSL_FORCE='no' SSL_HOME='same' LETSENCRYPT='no' FTP_USER='' FTP_MD5=''\
 BACKEND='$BACKEND_TEMPLATE' PROXY='$PROXY_TEMPLATE' PROXY_EXT='$PROXY_EXT'\
 STATS='' STATS_USER='' STATS_CRYPT='' U_DISK='0' U_BANDWIDTH='0'\
 SUSPENDED='no' TIME='$time' DATE='$date'" >> $USER_DATA/web.conf

syshealth_repair_web_config

# Restarting web server
$BIN/v-restart-web "$restart"
check_result $? "Web restart failed" > /dev/null

# Restarting proxy server
$BIN/v-restart-proxy "$restart"
check_result $? "Proxy restart failed" > /dev/null

# Logging
$BIN/v-log-action "$user" "Info" "Web" "Added new web domain (Name: $domain)."
log_event "$OK" "$ARGUMENTS"

exit