#!/bin/bash
# info: delete web domain SSL support
# options: USER DOMAIN [RESTART]
#
# example: v-delete-web-domain-ssl admin acme.com
#
# This function disable https support and deletes SSL certificates.

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

# Argument definition
user=$1
domain=$2
domain_idn=$2
restart=$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
# TODO: $domain_idn not used in this script - maybe $domain should be converted to $doman_idn ?

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

check_args '2' "$#" 'USER DOMAIN [RESTART]'
is_format_valid 'user' 'domain' 'restart'
is_system_enabled "$WEB_SYSTEM" 'WEB_SYSTEM'
is_object_valid 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_value_exist 'web' 'DOMAIN' "$domain" '$SSL'

# Perform verification if read-only mode is enabled
check_hestia_demo_mode

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

# Parsing domain values
get_domain_values 'web'

# Deleting domain
del_web_config "$WEB_SYSTEM" "$TPL.stpl"

# Checking proxy
if [ -n "$PROXY_SYSTEM" ] && [ -n "$PROXY" ]; then
	del_web_config "$PROXY_SYSTEM" "$PROXY.stpl"
fi

# Deleting old certificate
rm -f $HOMEDIR/$user/conf/web/$domain/ssl/$domain.*
rm -f $USER_DATA/ssl/$domain.ca
rm -f $USER_DATA/ssl/$domain.crt
rm -f $USER_DATA/ssl/$domain.key
rm -f $USER_DATA/ssl/$domain.pem

# Deleting force ssl
$BIN/v-delete-web-domain-ssl-force "$user" "$domain" 'no' 'yes'

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

# Update config
if [ -n "$LETSENCRYPT" ]; then
	update_object_value 'web' 'DOMAIN' "$domain" '$LETSENCRYPT' 'no'
fi
update_object_value 'web' 'DOMAIN' "$domain" '$SSL' 'no'

# Decreasing domain value
decrease_user_value "$user" '$U_WEB_SSL'

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

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

# Logging
$BIN/v-log-action "$user" "Warning" "Web" "SSL disabled (Domain: $domain)."
log_event "$OK" "$ARGUMENTS"

exit
