#!/usr/bin/env bash
set -euo pipefail

CERT_DIR="${CERT_DIR:-./certs}"
CERT_FILE="${CERT_DIR}/server.crt"
KEY_FILE="${CERT_DIR}/server.key"

mkdir -p "${CERT_DIR}"

cat >"${CERT_DIR}/openssl.cnf" <<'EOF'
[ req ]
default_bits       = 4096
distinguished_name = req_distinguished_name
req_extensions     = v3_req
prompt             = no

[ req_distinguished_name ]
C  = US
ST = Development
L  = Development
O  = ScarChat
CN = localhost

[ v3_req ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = localhost
DNS.2 = chat.scaritcolo.com
IP.1  = 127.0.0.1
IP.2  = 192.168.13.167
EOF

echo "Generating self-signed cert with SANs: localhost, chat.scaritcolo.com, 127.0.0.1, 192.168.13.167"
openssl req -x509 -nodes -days 365 \
  -newkey rsa:4096 \
  -keyout "${KEY_FILE}" \
  -out "${CERT_FILE}" \
  -config "${CERT_DIR}/openssl.cnf"

echo "Written cert: ${CERT_FILE}"
echo "Written key : ${KEY_FILE}"
echo "To trust for client: export SCARCHAT_CA=${CERT_FILE}"