#!/bin/bash
set -euo pipefail

if [ $# -ne 1 ]; then
  echo "Usage: $0 <DEVICE_GUID>"
  exit 1
fi

GUID="$1"

# Output files
KEY_FILE="device_${GUID}.key"
CSR_FILE="device_${GUID}.csr"
CONF_FILE="csr_${GUID}.conf"

# Generate config for CSR
cat > "$CONF_FILE" <<EOF
[ req ]
default_md     = sha256
prompt         = no
distinguished_name = dn
req_extensions = req_ext

[ dn ]
CN = $GUID

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
URI.1 = urn:device:$GUID
EOF

# Generate private key
openssl ecparam -name prime256v1 -genkey -noout -out "$KEY_FILE"
chmod 600 "$KEY_FILE"

# Generate CSR
openssl req -new -key "$KEY_FILE" -out "$CSR_FILE" -config "$CONF_FILE"