#!/bin/bash

# Identify the OS
os=$(cat /etc/os-release | grep ^NAME | cut -d= -f2 | tr -d '"')

# Function to check certificate length
check_cert_length() {
    cert_file=$1
    if [[ -f "$cert_file" ]]; then
        echo "Checking certificate: $cert_file"

        # Get the certificate's key length (e.g., Public-Key: (2048 bit))
        cert_length=$(openssl x509 -in "$cert_file" -text -noout | grep "Public-Key" | awk -F'(' '{print $2}' | awk '{print $1}')

        # Ensure cert_length is numeric and check if it's less than 2048 bits
        if [[ "$cert_length" =~ ^[0-9]+$ ]]; then
            if [[ "$cert_length" -lt 2048 ]]; then
                echo -e "\e[31mYour SSL certificate has a key length below 2048 bits. For better security, please generate a new certificate with a key length of at least 2048 bits.\e[0m"
		echo -e "\e[31mSystem not ready for upgrade.\e[0m"
		echo -e "\e[31mIf you need assistance, contact support.\e[0m"
	    else
            	echo -e "\e[32mCertificate length: $cert_length bits. You can proceed with the FileCloud Installation/Upgrade.\e[0m"
	    fi
        else
        	echo -e "\e[33mFailed to extract a valid certificate length from $cert_file.\e[0m"
	fi
    else
        echo -e "\e[33mCertificate file not found: $cert_file.\e[0m"
    fi
}

# Check SSL configurations based on OS
if [[ "$os" == "Ubuntu" ]]; then
    # Check if SSL configuration exists in 000-default.conf
    ssl_file=$(grep -i "SSLCertificateFile" /etc/apache2/sites-enabled/000-default.conf | grep -vE '^\s*#|^\s*$' | awk '{print $2}' | sed 's/^[ \t]*//;s/[ \t]*$//')
    if [[ -z "$ssl_file" ]]; then
        echo -e "\e[31mSSL configuration not found in /etc/apache2/sites-enabled/000-default.conf. If you have installed SSL on a custom path please ensure the certificate length is equal to or above 2048 bits. If you need assistance, contact support.\e[0m"
    else
        check_cert_length "$ssl_file"
    fi
elif [[ "$os" == "Red Hat Enterprise Linux" ]]; then
    # Check if SSL configuration exists in ssl.conf
    ssl_file=$(grep -i "SSLCertificateFile" /etc/httpd/conf.d/ssl.conf | grep -vE '^\s*#|^\s*$' | awk '{print $2}' | sed 's/^[ \t]*//;s/[ \t]*$//')
    if [[ -z "$ssl_file" ]]; then
        echo -e "\e[31mSSL configuration not found in /etc/httpd/conf.d/ssl.conf. If you have installed SSL on a custom path please ensure the certificate length is equal to or above 2048 bits. If you need assistance, contact support.\e[0m"
    else
        check_cert_length "$ssl_file"
    fi
else
    echo "Unsupported OS: $os"
fi
