#!/bin/bash
# info: delete web domain SSL support
# options: USER DOMAIN
#
# The function disable https support and deletes SSL certificates.


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

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

# Includes
source $VESTA/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/conf/vesta.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'
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"
is_object_value_exist 'web' 'DOMAIN' "$domain" '$SSL'


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

# Parsing domain values
get_domain_values 'web'

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

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

# Deleting old certificate
tmpdir=$(mktemp -p $HOMEDIR/$user/web/$domain/private -d)

# remove certificate files - do not use wildcard, as this might remove other domains
rm -f $HOMEDIR/$user/conf/web/ssl.$domain.ca
rm -f $HOMEDIR/$user/conf/web/ssl.$domain.crt
rm -f $HOMEDIR/$user/conf/web/ssl.$domain.key
rm -f $HOMEDIR/$user/conf/web/ssl.$domain.pem

mv $USER_DATA/ssl/$domain.* $tmpdir
chown -R $user:$user $tmpdir


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

# Update config
if [ ! -z "$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
log_history "disabled ssl support for $domain"
log_event "$OK" "$ARGUMENTS"

exit
