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


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

# Argument defenition
user=$1
domain=$(idn -t --quiet -u "$2" )
domain_idn=$(idn -t --quiet -a "$domain")
restart=$3

# Includes
source $VESTA/func/main.sh
source $VESTA/func/domain.sh
source $VESTA/conf/vesta.conf


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

check_args '2' "$#" 'USER DOMAIN'
validate_format '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'
conf="$HOMEDIR/$user/conf/web/s$WEB_SYSTEM.conf"
tpl_file="$WEBTPL/$WEB_SYSTEM/$TPL.stpl"

# Deleting domain
del_web_config

# Checking proxy
if [ ! -z "$PROXY" ]; then
    conf="$HOMEDIR/$user/conf/web/s$PROXY_SYSTEM.conf"
    tpl_file="$WEBTPL/$PROXY_SYSTEM/$PROXY.stpl"
    del_web_config
fi

# Deleting old certificate
tmpdir=$(mktemp -p $HOMEDIR/$user/web/$domain/private -d)
rm -f $HOMEDIR/$user/conf/web/ssl.$domain.*
mv $USER_DATA/ssl/$domain.* $tmpdir
chown -R $user:$user $tmpdir


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

# Update config
update_object_value 'web' 'DOMAIN' "$domain" '$SSL' 'no'

# Checking last SSL domain
ssl_dom=$(grep "SSL='yes'" $USER_DATA/web.conf)
conf="/etc/$WEB_SYSTEM/conf.d/vesta.conf"
if [ -z "$ssl_dom" ]; then
    sed -i "/.*\/$user\/.*s$WEB_SYSTEM.conf/d" $conf
    rm -f $HOMEDIR/$user/conf/web/s$WEB_SYSTEM.conf

fi

# Checking proxy
if [ ! -z "$PROXY_SYSTEM" ]; then
    conf="/etc/$PROXY_SYSTEM/conf.d/vesta.conf"
    if [ -z "$ssl_dom" ]; then
        sed -i "/.*\/$user\/.*s$PROXY_SYSTEM.conf/d" $conf
        rm -f $HOMEDIR/$user/conf/web/s$PROXY_SYSTEM.conf
    fi
fi

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

# Restart web server
if [ "$restart" != 'no' ]; then
    $BIN/v-restart-web
    if [ $? -ne 0 ]; then
        exit $E_RESTART
    fi

    $BIN/v-restart-proxy
    if [ $? -ne 0 ]; then
        exit $E_RESTART
    fi
fi

# Logging
log_history "disabled ssl support for $domain"
log_event "$OK" "$EVENT"

exit
