#!/bin/bash

EXPIRY_DURATION=365 #days
AUTHORITY_DURATION=$(( $EXPIRY_DURATION * 3 ))

# 1. Root CA (v3)
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -sha256 -days "$AUTHORITY_DURATION" -out ca.pem -subj "/CN=ChirpStack-CA"

# 2. Server cert (Mosquitto) v3
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr -subj "/CN=mosquitto"

# Add v3 extensions for rustls
cat >server_ext.cnf <<EOF
basicConstraints=CA:FALSE
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = DNS:mosquitto
EOF

openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial \
-out server.pem -days "$EXPIRY_DURATION" -sha256 -extfile server_ext.cnf

# 3. Client cert (ChirpStack + Gateway Bridge) v3
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr -subj "/CN=chirpstack"

cat >client_ext.cnf <<EOF
basicConstraints=CA:FALSE
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth
EOF

openssl x509 -req -in client.csr -CA ca.pem -CAkey ca.key -CAcreateserial \
-out client.pem -days "$EXPIRY_DURATION" -sha256 -extfile client_ext.cnf

# 4. Allow docker to read files
sudo chmod 644 *.pem
sudo chmod 644 *.key
sudo chmod 644 *.csr
