#!/bin/bash

checkSSLCertsRequirement()
{  
	if [[ $CFG_REQUIREMENT_SSLCERTS == "true" ]]; then
		### SSL Certificates
		# 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

		# Check for missing certificates
		missing_ssl=()
		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
				isSuccessful "Certificate for domain $domain_value installed."
			else
				missing_ssl+=("$domain_value")
				isNotice "Certificate for domain $domain_value not found."
			fi
		done

		# Check for obsolete certificates that need removal
		obsolete_ssl=()
		for existing_domain in "${existing_domains[@]}"; do
			# Skip if this domain is still configured
			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
				obsolete_ssl+=("$existing_domain")
				isNotice "Certificate for domain $existing_domain is no longer configured and will be removed."
			fi
		done

		# Determine if SSL setup is needed
		if [ ${#missing_ssl[@]} -eq 0 ] && [ ${#obsolete_ssl[@]} -eq 0 ]; then
			isSuccessful "SSL certificates are setup correctly for all domains."
			SkipSSLInstall=true
		else
			if [ ${#missing_ssl[@]} -gt 0 ]; then
				isNotice "SSL certificates are missing for domains: ${missing_ssl[*]}"
			fi
			if [ ${#obsolete_ssl[@]} -gt 0 ]; then
				isNotice "SSL certificates will be removed for domains: ${obsolete_ssl[*]}"
			fi
			((preinstallneeded++)) 
		fi
	fi
} 