#!/bin/bash
# Generate AS4 Certificates
# Creates TLS, signing, and encryption certificates for AS4 Settlement

set -e

CERT_DIR="${AS4_CERT_DIR:-./certs/as4}"
DAYS_VALID="${AS4_CERT_DAYS:-365}"

echo "========================================="
echo "AS4 Certificate Generation"
echo "========================================="

# Create certificate directory
mkdir -p "$CERT_DIR"
chmod 700 "$CERT_DIR"

echo ""
echo "Generating certificates in: $CERT_DIR"
echo "Validity: $DAYS_VALID days"
echo ""

# Generate TLS Certificate
echo "1. Generating TLS Certificate..."
openssl req -x509 -newkey rsa:2048 \
  -keyout "$CERT_DIR/as4-tls-key.pem" \
  -out "$CERT_DIR/as4-tls-cert.pem" \
  -days "$DAYS_VALID" -nodes \
  -subj "/CN=as4.dbis.org/O=DBIS/C=US/ST=DC/L=Washington" 2>/dev/null

chmod 600 "$CERT_DIR/as4-tls-key.pem"
chmod 644 "$CERT_DIR/as4-tls-cert.pem"

# Calculate TLS fingerprint
TLS_FINGERPRINT=$(openssl x509 -fingerprint -sha256 -noout -in "$CERT_DIR/as4-tls-cert.pem" | cut -d'=' -f2 | tr -d ':')
echo "   TLS Fingerprint: $TLS_FINGERPRINT"

# Generate Signing Certificate
echo ""
echo "2. Generating Signing Certificate..."
openssl req -x509 -newkey rsa:2048 \
  -keyout "$CERT_DIR/as4-signing-key.pem" \
  -out "$CERT_DIR/as4-signing-cert.pem" \
  -days "$DAYS_VALID" -nodes \
  -subj "/CN=DBIS AS4 Signing/O=DBIS/C=US/ST=DC/L=Washington" 2>/dev/null

chmod 600 "$CERT_DIR/as4-signing-key.pem"
chmod 644 "$CERT_DIR/as4-signing-cert.pem"

# Calculate signing fingerprint
SIGNING_FINGERPRINT=$(openssl x509 -fingerprint -sha256 -noout -in "$CERT_DIR/as4-signing-cert.pem" | cut -d'=' -f2 | tr -d ':')
echo "   Signing Fingerprint: $SIGNING_FINGERPRINT"

# Generate Encryption Certificate
echo ""
echo "3. Generating Encryption Certificate..."
openssl req -x509 -newkey rsa:2048 \
  -keyout "$CERT_DIR/as4-encryption-key.pem" \
  -out "$CERT_DIR/as4-encryption-cert.pem" \
  -days "$DAYS_VALID" -nodes \
  -subj "/CN=DBIS AS4 Encryption/O=DBIS/C=US/ST=DC/L=Washington" 2>/dev/null

chmod 600 "$CERT_DIR/as4-encryption-key.pem"
chmod 644 "$CERT_DIR/as4-encryption-cert.pem"

# Calculate encryption fingerprint
ENCRYPTION_FINGERPRINT=$(openssl x509 -fingerprint -sha256 -noout -in "$CERT_DIR/as4-encryption-cert.pem" | cut -d'=' -f2 | tr -d ':')
echo "   Encryption Fingerprint: $ENCRYPTION_FINGERPRINT"

# Save fingerprints to file
cat > "$CERT_DIR/fingerprints.txt" <<EOF
# AS4 Certificate Fingerprints
# Generated: $(date -Iseconds)

TLS_FINGERPRINT=$TLS_FINGERPRINT
SIGNING_FINGERPRINT=$SIGNING_FINGERPRINT
ENCRYPTION_FINGERPRINT=$ENCRYPTION_FINGERPRINT
EOF

echo ""
echo "========================================="
echo "Certificate Generation Complete!"
echo "========================================="
echo ""
echo "Certificates saved to: $CERT_DIR"
echo "Fingerprints saved to: $CERT_DIR/fingerprints.txt"
echo ""
echo "Next steps:"
echo "1. Update .env with certificate paths"
echo "2. Update .env with fingerprints"
echo "3. Register certificates in Member Directory"
echo ""
