#!/bin/bash
# info: change domain ssl certificate
# options: USER DOMAIN SSL_DIR [RESTART]
#
# The function changes SSL domain certificate and the key. If ca file present
# it will be replaced as well.


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

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

# 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 '3' "$#" 'USER DOMAIN SSL_DIR [RESTART]'
is_format_valid 'user' 'domain' 'ssl_dir'
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'
is_web_domain_cert_valid


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

# 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

# Adding new certificate to user data directory
cp -f $ssl_dir/$domain.crt $USER_DATA/ssl/$domain.crt
cp -f $ssl_dir/$domain.key $USER_DATA/ssl/$domain.key
cp -f $ssl_dir/$domain.crt $USER_DATA/ssl/$domain.pem
if [ -e "$ssl_dir/$domain.ca" ]; then
    cp -f $ssl_dir/$domain.ca $USER_DATA/ssl/$domain.ca
    cat $USER_DATA/ssl/$domain.ca >> $USER_DATA/ssl/$domain.pem
fi

# Adding new certificate to user dir
cp -f $USER_DATA/ssl/$domain.crt $HOMEDIR/$user/conf/web/ssl.$domain.crt
cp -f $USER_DATA/ssl/$domain.key $HOMEDIR/$user/conf/web/ssl.$domain.key
cp -f $USER_DATA/ssl/$domain.pem $HOMEDIR/$user/conf/web/ssl.$domain.pem
if [ -e "$USER_DATA/ssl/$domain.ca" ]; then
    cp -f $USER_DATA/ssl/$domain.ca $HOMEDIR/$user/conf/web/ssl.$domain.ca
fi


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

# 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 "changed ssl certificate for $domain"
log_event "$OK" "$ARGUMENTS"

exit
