#!/bin/bash
#
# Copyright (c) 2021-2024 NVIDIA CORPORATION & AFFILIATES, ALL RIGHTS RESERVED.
#
# This software product is a proprietary product of NVIDIA CORPORATION &
# AFFILIATES (the "Company") and all right, title, and interest in and to the
# software product, including all associated intellectual property rights, are
# and shall remain exclusively with the Company.
#
# This software product is governed by the End User License Agreement
# provided with the software product.
#
# Define directories
PRIVATE_KEY_DIR="/etc/ssl/private/blueman/"
CERT_DIR="/etc/ssl/certs/blueman/"

# Ensure directories exist
mkdir -p "$PRIVATE_KEY_DIR"
mkdir -p "$CERT_DIR"

# Define file paths
PRIVATE_KEY="${PRIVATE_KEY_DIR}server.key"
CERTIFICATE="${CERT_DIR}server.crt"

# Function to generate the san.cnf file
generate_san_cnf() {
    cat > san.cnf << EOF
[ req ]
default_bits       = 4096
prompt             = no
default_md         = sha256
req_extensions     = req_ext
distinguished_name = dn

[ dn ]
C  = US
ST = State
L  = Locality
O  = Organization
OU = Organizational Unit
CN = your.domain.com

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = your.domain.com
DNS.2 = www.your.domain.com
EOF
}

# Check if both the private key and certificate already exist
if [ -f "$PRIVATE_KEY" ] && [ -f "$CERTIFICATE" ]; then
    echo "Both private key and certificate already exist. Exiting."
    exit 0
fi

# Generate the private key
openssl genrsa -out "$PRIVATE_KEY" 4096
echo "Private key created at: $PRIVATE_KEY"
echo "change mode of private key to 644"
chmod 644 $PRIVATE_KEY

# Generate the certificate
# Generate the san.cnf file
generate_san_cnf

# Generate the CSR
openssl req -new -key "$PRIVATE_KEY" -out server.csr -config san.cnf

# Generate the self-signed certificate
openssl x509 -req -in server.csr -signkey "$PRIVATE_KEY" -out "$CERTIFICATE" -days 365 -extensions req_ext -extfile san.cnf

# Clean up temporary files
rm san.cnf server.csr

echo "Certificate created at: $CERTIFICATE"
