#!/bin/bash
# info: enable/disable directory listing
# options: USER DOMAIN MODE
#
# example: v-change-web-domain-dirlist user demo.com on
#
# This function is used for changing the directory list mode.

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

# Argument defenition
user=$1
domain=$2
mode=$3

# 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
# load config file
source_conf "$HESTIA/conf/hestia.conf"

# Additional argument formatting
format_domain
format_domain_idn

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

check_args '3' "$#" 'USER DOMAIN MODE'
is_format_valid 'user' 'domain'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"
get_domain_values 'web'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Fetching domain variables
get_domain_values 'web'

if [ "$mode" = "on" ]; then
	# Enable directory listing
	sed -i "s/-Index/+Index/g" $HOMEDIR/$user/conf/web/$domain/$WEB_SYSTEM.conf
	if [ "$SSL" == "yes" ]; then
		# Enable directory listing for SSL-enforced domains
		sed -i "s/-Index/+Index/g" $HOMEDIR/$user/conf/web/$domain/$WEB_SYSTEM.ssl.conf
	fi
	echo "Enabled directory browsing for $domain."
else
	# Disable directory listing
	sed -i "s/+Index/-Index/g" $HOMEDIR/$user/conf/web/$domain/$WEB_SYSTEM.conf
	if [ "$SSL" == "yes" ]; then
		# Enable directory listing for SSL-enforced domains
		sed -i "s/+Index/-Index/g" $HOMEDIR/$user/conf/web/$domain/$WEB_SYSTEM.ssl.conf
	fi
	echo "Disabled directory browsing for $domain."
fi

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

# Rebuilding vhosts
$BIN/v-restart-web

# Logging
if [ "$mode" = "on" ]; then
	$BIN/v-log-action "$user" "Warning" "Web" "Directory browsing enabled (Domain: $domain)."
else
	$BIN/v-log-action "$user" "Info" "Web" "Directory browsing disabled (Domain: $domain)."
fi
log_event "$OK" "$EVENT"

exit