#!/bin/bash

installSSLCertificate()
{
	if [[ "$CFG_REQUIREMENT_SSLCERTS" == "true" ]]; then
        if [[ "$SkipSSLInstall" != "true" ]]; then
            isHeader "Install SSL Certificate"

            # Get current configured domains
            configured_domains=()
            for domain_num in {1..9}; do
                domain_var="CFG_DOMAIN_$domain_num"
                domain_value="${!domain_var}"
                if [ -n "$domain_value" ]; then
                    configured_domains+=("$domain_value")
                fi
            done

            # Get existing certificate domains
            existing_domains=()
            if [ -d "$ssl_dir" ]; then
                for cert_file in "$ssl_dir"/*.crt; do
                    if [ -f "$cert_file" ]; then
                        domain_name=$(basename "$cert_file" .crt)
                        existing_domains+=("$domain_name")
                    fi
                done
            fi

            # Function to generate SSL certificate for a given domain
            generateSSLCertificate() {
                local domain_value="$1"
                local result=$(cd $ssl_dir && openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -subj "/CN=$domain_value" -keyout "$ssl_dir/$domain_value.key" -out "$ssl_dir/$domain_value.crt" > /dev/null 2>&1)
                checkSuccess "SSL Generation for $domain_value"
            }

            # Remove obsolete certificates first
            for existing_domain in "${existing_domains[@]}"; do
                is_still_configured=false
                for configured_domain in "${configured_domains[@]}"; do
                    if [ "$existing_domain" == "$configured_domain" ]; then
                        is_still_configured=true
                        break
                    fi
                done
                
                if [ "$is_still_configured" == false ]; then
                    isNotice "Removing obsolete SSL certificate for $existing_domain..."
                    rm -f "$ssl_dir/$existing_domain.key" "$ssl_dir/$existing_domain.crt"
                    checkSuccess "Removed obsolete certificate for $existing_domain"
                fi
            done

            # Generate SSL certificates for missing domains
            for domain_value in "${configured_domains[@]}"; do
                key_file="$ssl_dir/$domain_value.key"
                crt_file="$ssl_dir/$domain_value.crt"
                
                if [ ! -f "$key_file" ] || [ ! -f "$crt_file" ]; then
                    isNotice "Creating SSL certificate for $domain_value..."
                    generateSSLCertificate "$domain_value"
                else
                    isSuccessful "Certificate for $domain_value already exists and is valid."
                fi
            done

            sslcertchoice=n
        fi
    fi
}
