#!/bin/bash
# Script to generate a CA cert/key and a device/server cert signed by this CA
# Outputs: ca_cert.pem, ca_key.pem, device_cert.pem, device_key.pem

CA_DIR=certs/ca
mkdir -p "$CA_DIR"
CA_CERT=$CA_DIR/ca_cert.pem
CA_KEY=$CA_DIR/ca_key.pem

# Generate CA key and cert (20 year expiry)
echo "Generating CA key and certificate (20 year expiry)..."
openssl req -x509 -newkey rsa:4096 -days 7300 -nodes -subj "/CN=SummitWaveCA" -keyout "$CA_KEY" -out "$CA_CERT"

# PEM version (for most browsers)
cp "$CA_CERT" "$CA_DIR/ca_cert.crt"
# DER version (for Windows)
openssl x509 -in "$CA_CERT" -outform der -out "$CA_DIR/ca_cert.der"

# Output summary
echo "CA cert: $CA_CERT"
echo "CA cert (CRT for browser import): $CA_DIR/ca_cert.crt"
echo "CA key: $CA_KEY"
echo "Distribute $CA_CERT or $CA_DIR/ca_cert.crt to clients to trust this device."
echo "Keep $CA_KEY secret and offline except when signing device CSRs."
echo "CA cert: $CA_CERT"
echo "CA cert (CRT for browser import): $CERT_DIR/ca_cert.crt"
echo "CA key: $CA_KEY"
echo "Device cert: $DEVICE_CERT"
echo "Device key: $DEVICE_KEY"
echo "Distribute $CA_CERT or $CERT_DIR/ca_cert.crt to clients to trust this device."
