#!/bin/bash
# info: Adding force SSL for a domain
# options: USER DOMAIN
#
# The function forces SSL for the requested domain.


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

# Argument definition
user=$1
domain=$2

# Includes
source $HESTIA/func/main.sh
source $HESTIA/conf/hestia.conf


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

check_args '2' "$#" 'USER DOMAIN'
is_format_valid 'user' 'domain'
is_object_valid 'user' 'USER' "$user"
is_object_unsuspended 'user' 'USER' "$user"
is_object_valid 'web' 'DOMAIN' "$domain"
is_object_unsuspended 'web' 'DOMAIN' "$domain"

# Perform verification if read-only mode is enabled
check_hestia_demo_mode


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

# Load domain data
parse_object_kv_list $(grep "DOMAIN='$domain'" $USER_DATA/web.conf)

# Check if SSL is enabled
if [ "$SSL" != 'yes' ]; then
    echo "Error: SSL is not enabled"
    exit $E_NOTEXIST
fi

# Check if proxy is active
if [ ! -z "$PROXY_SYSTEM" ]; then
    if ! grep --quiet "forcessl" $HESTIA/data/templates/web/nginx/default.tpl; then
        $BIN/v-update-web-templates
    fi
    forcessl="$HOMEDIR/$user/conf/web/$domain/$PROXY_SYSTEM.forcessl.conf"
else
    if ! grep --quiet "forcessl" $HESTIA/data/templates/web/nginx/default.tpl; then
        $BIN/v-update-web-templates
    fi
    forcessl="$HOMEDIR/$user/conf/web/$domain/$WEB_SYSTEM.forcessl.conf"
fi

# Insert redirect commands
if [ ! -z "$PROXY_SYSTEM" ] || [ "$WEB_SYSTEM" = 'nginx' ]; then
    echo 'return 301 https://$host$request_uri;' > $forcessl
else
    echo 'RewriteEngine On' > $forcessl
    echo 'RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]' >> $forcessl
fi


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

if [ -z "$SSL_FORCE" ]; then
    add_object_key "web" 'DOMAIN' "$domain" 'SSL_FORCE' 'SSL_HOME'
fi

# Set forcessl flag to enabled
update_object_value 'web' 'DOMAIN' "$domain" '$SSL_FORCE' 'yes'

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

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

# Logging
log_history "enabled automatic HTTP-to-HTTPS redirection for $domain"
log_event "$OK" "$ARGUMENTS"

exit
