#!/bin/bash
#
# issue-cert.sh — issue a leaf certificate from the fleet intermediate [#697]
# Usage: issue-cert.sh <common-name> "SAN list"   e.g.
#   issue-cert.sh tsys-wazuh.knel.net "DNS:tsys-wazuh.knel.net,DNS:tsys-siem.knel.net"
# Requires: intermediate initialized at /etc/ssl/tsys-ca (ca-init.sh).
# Output: <certs>/<cn>.crt (leaf+chain) + <certs>/<cn>.key (0600) on this host.
#
set -euo pipefail

CN="${1:?usage: issue-cert.sh <common-name> \"SAN list\"}"
SAN="${2:?usage: issue-cert.sh <common-name> \"SAN list\"}"
INT_DIR="${INT_DIR:-/etc/ssl/tsys-ca}"
INT_KEY="$INT_DIR/intermediate.key"
INT_CRT="$INT_DIR/intermediate.crt"
CHAIN="$INT_DIR/ca-chain.crt"

[ -s "$INT_CRT" ] || { echo "intermediate missing at $INT_CRT — run ca-init.sh first" >&2; exit 1; }
[ -s "$INT_KEY" ] || { echo "intermediate key missing" >&2; exit 1; }

KEY="$INT_DIR/certs/$CN.key"
CSR="$INT_DIR/csr/$CN.csr"
CRT="$INT_DIR/certs/$CN.crt"
[ -e "$CRT" ] && { echo "cert already exists: $CRT (revoke/rename first)" >&2; exit 1; }

openssl genrsa -out "$KEY" 2048 2>/dev/null
chmod 600 "$KEY"
openssl req -new -key "$KEY" -out "$CSR" -sha256 \
  -subj "/C=US/ST=Texas/O=Known Element Enterprises/OU=TechOps/CN=$CN"
openssl x509 -req -in "$CSR" -CA "$INT_CRT" -CAkey "$INT_KEY" \
  -CAcreateserial -days 825 -sha256 -out "$CRT" \
  -extfile <(printf 'basicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=%s\nauthorityKeyIdentifier=keyid,issuer\n' "$SAN")

cat "$CRT" "$CHAIN" > "$INT_DIR/certs/$CN.fullchain"
openssl verify -CAfile "$CHAIN" "$CRT"
echo "issued: $CRT (+ .key, .csr, .fullchain)"
