#!/bin/bash

# Configuration settings matching OPC UA requirements
OUTPUT_DIR="./project/certificates"

mkdir -p "$OUTPUT_DIR"

echo "=================================================="
echo "Generating Cryptographic Nodes for open62541"
echo "=================================================="

# Generate a secure 2048-bit RSA Private Key
openssl genrsa -out "$OUTPUT_DIR/server_key.pem" 2048

# Create a custom configuration file for the X.509 Certificate Extensions
# OPC UA mandates the Application URI inside the Subject Alternative Name (SAN)
cat <<EOF > "$OUTPUT_DIR/cert_config.cnf"
[ req ]
default_bits        = 2048
default_md          = sha256
distinguished_name  = req_distinguished_name
x509_extensions     = v3_ca
prompt              = no

[ req_distinguished_name ]
countryName            = AA
stateOrProvinceName    = EARTH
localityName           = EARTH
organizationName       = EARTH
commonName             = TM4C_OPCUA_Server

[ v3_ca ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, keyCertSign
extendedKeyUsage = TLS Web Server Authentication, TLS Web Client Authentication
subjectAltName = URI:urn:open62541:server:tiva
EOF


# Generate a compliant private key (PKCS#1 format)
openssl genrsa -out "$OUTPUT_DIR/server_key.pem" 2048

# Generate the self-signed certificate using your custom configuration profile
# Force OpenSSL to create a V3 certificate by passing -extfile and -extensions together
openssl req -x509 -new -nodes \
  -key "$OUTPUT_DIR/server_key.pem" \
  -days 3650 \
  -out "$OUTPUT_DIR/server_cert.pem" \
  -config "$OUTPUT_DIR/cert_config.cnf" \
  -batch


echo "Converting to DER"
openssl x509 -in "$OUTPUT_DIR/server_cert.pem" -outform DER -out "$OUTPUT_DIR/server_cert.der"
openssl rsa -in "$OUTPUT_DIR/server_key.pem" -traditional -outform DER -out "$OUTPUT_DIR/server_key.der"

echo "Converting keys to native C byte-arrays..."

# 4. Use xxd to convert the PEM files directly into C array code formatting
xxd -i "$OUTPUT_DIR/server_cert.pem" > "$OUTPUT_DIR/server_cert.c"
xxd -i "$OUTPUT_DIR/server_key.pem" > "$OUTPUT_DIR/server_key.c"
xxd -i "$OUTPUT_DIR/server_cert.der" > "$OUTPUT_DIR/server_cert_der.c"
xxd -i "$OUTPUT_DIR/server_key.der" > "$OUTPUT_DIR/server_key_der.c"

# 5. Clean up temporary text artifacts
# rm "$OUTPUT_DIR/cert_config.cnf"

echo "--------------------------------------------------"
echo "SUCCESS: Certificate structures created inside $OUTPUT_DIR"
echo "=================================================="
