#!/usr/bin/env bash

# Generate TLS certificates for Mailu service
# This script creates a self-signed certificate for mail.bakery-ia.dev
# For production, you should use Let's Encrypt or a trusted CA

set -e

TLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MAIL_DIR="$TLS_DIR/mail"

mkdir -p "$MAIL_DIR"

echo "Generating TLS certificates for Mailu service..."
echo "Directory: $MAIL_DIR"
echo ""

# Clean up old certificates
rm -f "$MAIL_DIR/tls.key" "$MAIL_DIR/tls.crt" 2>/dev/null || true

# Generate private key
openssl genrsa -out "$MAIL_DIR/tls.key" 2048

# Generate self-signed certificate valid for 365 days
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout "$MAIL_DIR/tls.key" -out "$MAIL_DIR/tls.crt" \
  -subj "/CN=mail.bakery-ia.dev/O=Bakery IA"

echo "✓ Mailu certificates generated"
echo ""

# Verify certificate
echo "Certificate details:"
openssl x509 -in "$MAIL_DIR/tls.crt" -noout -subject -issuer -dates

echo ""
echo "==================="
echo "✓ Certificate generated successfully!"
echo ""
echo "Generated files:"
echo "  - $MAIL_DIR/tls.crt (Certificate)"
echo "  - $MAIL_DIR/tls.key (Private key)"
echo ""
echo "Next steps:"
echo "  1. Create Kubernetes secret: kubectl create secret tls mailu-certificates --cert=$MAIL_DIR/tls.crt --key=$MAIL_DIR/tls.key -n bakery-ia"
echo "  2. Update the mailu-certificates-secret.yaml with the base64 encoded values"
echo "  3. Apply the secret to your cluster"
