#!/usr/bin/env bash

# Generate TLS certificates for PostgreSQL and Redis
# Self-signed certificates for internal cluster use

set -e

TLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CA_DIR="$TLS_DIR/ca"
POSTGRES_DIR="$TLS_DIR/postgres"
REDIS_DIR="$TLS_DIR/redis"

echo "Generating TLS certificates for Bakery IA..."
echo "Directory: $TLS_DIR"
echo ""

# Clean up old certificates
echo "Cleaning up old certificates..."
rm -rf "$CA_DIR"/* "$POSTGRES_DIR"/* "$REDIS_DIR"/* 2>/dev/null || true

# =====================================
# 1. Generate Certificate Authority (CA)
# =====================================

echo "Step 1: Generating Certificate Authority (CA)..."

# Generate CA private key
openssl genrsa -out "$CA_DIR/ca-key.pem" 4096

# Generate CA certificate (valid for 10 years)
openssl req -new -x509 -days 3650 -key "$CA_DIR/ca-key.pem" -out "$CA_DIR/ca-cert.pem" \
  -subj "/C=US/ST=California/L=SanFrancisco/O=BakeryIA/OU=Security/CN=BakeryIA-CA"

echo "✓ CA certificate generated"
echo ""

# =====================================
# 2. Generate PostgreSQL Server Certificates
# =====================================

echo "Step 2: Generating PostgreSQL server certificates..."

# Generate PostgreSQL server private key
openssl genrsa -out "$POSTGRES_DIR/server-key.pem" 4096

# Create certificate signing request (CSR)
openssl req -new -key "$POSTGRES_DIR/server-key.pem" -out "$POSTGRES_DIR/server.csr" \
  -subj "/C=US/ST=California/L=SanFrancisco/O=BakeryIA/OU=Database/CN=*.bakery-ia.svc.cluster.local"

# Create SAN (Subject Alternative Names) configuration
cat > "$POSTGRES_DIR/san.cnf" <<EOF
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no

[req_distinguished_name]
C = US
ST = California
L = SanFrancisco
O = BakeryIA
OU = Database
CN = *.bakery-ia.svc.cluster.local

[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = *.bakery-ia.svc.cluster.local
DNS.2 = *.bakery-ia
DNS.3 = auth-db-service
DNS.4 = tenant-db-service
DNS.5 = training-db-service
DNS.6 = forecasting-db-service
DNS.7 = sales-db-service
DNS.8 = external-db-service
DNS.9 = notification-db-service
DNS.10 = inventory-db-service
DNS.11 = recipes-db-service
DNS.12 = suppliers-db-service
DNS.13 = pos-db-service
DNS.14 = orders-db-service
DNS.15 = production-db-service
DNS.16 = alert-processor-db-service
DNS.17 = localhost
IP.1 = 127.0.0.1
EOF

# Sign the certificate with CA (valid for 3 years)
openssl x509 -req -in "$POSTGRES_DIR/server.csr" \
  -CA "$CA_DIR/ca-cert.pem" -CAkey "$CA_DIR/ca-key.pem" -CAcreateserial \
  -out "$POSTGRES_DIR/server-cert.pem" -days 1095 \
  -extensions v3_req -extfile "$POSTGRES_DIR/san.cnf"

# PostgreSQL requires specific permissions on key file
chmod 600 "$POSTGRES_DIR/server-key.pem"
chmod 644 "$POSTGRES_DIR/server-cert.pem"

# Copy CA cert for PostgreSQL clients
cp "$CA_DIR/ca-cert.pem" "$POSTGRES_DIR/ca-cert.pem"

echo "✓ PostgreSQL certificates generated"
echo ""

# =====================================
# 3. Generate Redis Server Certificates
# =====================================

echo "Step 3: Generating Redis server certificates..."

# Generate Redis server private key
openssl genrsa -out "$REDIS_DIR/redis-key.pem" 4096

# Create certificate signing request (CSR)
openssl req -new -key "$REDIS_DIR/redis-key.pem" -out "$REDIS_DIR/redis.csr" \
  -subj "/C=US/ST=California/L=SanFrancisco/O=BakeryIA/OU=Cache/CN=redis-service.bakery-ia.svc.cluster.local"

# Create SAN configuration for Redis
cat > "$REDIS_DIR/san.cnf" <<EOF
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no

[req_distinguished_name]
C = US
ST = California
L = SanFrancisco
O = BakeryIA
OU = Cache
CN = redis-service.bakery-ia.svc.cluster.local

[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = redis-service.bakery-ia.svc.cluster.local
DNS.2 = redis-service.bakery-ia
DNS.3 = redis-service
DNS.4 = localhost
IP.1 = 127.0.0.1
EOF

# Sign the certificate with CA (valid for 3 years)
openssl x509 -req -in "$REDIS_DIR/redis.csr" \
  -CA "$CA_DIR/ca-cert.pem" -CAkey "$CA_DIR/ca-key.pem" -CAcreateserial \
  -out "$REDIS_DIR/redis-cert.pem" -days 1095 \
  -extensions v3_req -extfile "$REDIS_DIR/san.cnf"

# Redis requires specific permissions
chmod 600 "$REDIS_DIR/redis-key.pem"
chmod 644 "$REDIS_DIR/redis-cert.pem"

# Copy CA cert for Redis clients
cp "$CA_DIR/ca-cert.pem" "$REDIS_DIR/ca-cert.pem"

echo "✓ Redis certificates generated"
echo ""

# =====================================
# 4. Verify Certificates
# =====================================

echo "Step 4: Verifying certificates..."

# Verify PostgreSQL certificate
echo "PostgreSQL certificate details:"
openssl x509 -in "$POSTGRES_DIR/server-cert.pem" -noout -subject -issuer -dates
openssl verify -CAfile "$CA_DIR/ca-cert.pem" "$POSTGRES_DIR/server-cert.pem"

echo ""
echo "Redis certificate details:"
openssl x509 -in "$REDIS_DIR/redis-cert.pem" -noout -subject -issuer -dates
openssl verify -CAfile "$CA_DIR/ca-cert.pem" "$REDIS_DIR/redis-cert.pem"

echo ""
echo "===================="
echo "✓ All certificates generated successfully!"
echo ""
echo "Generated files:"
echo "  CA:"
echo "    - $CA_DIR/ca-cert.pem (Certificate Authority certificate)"
echo "    - $CA_DIR/ca-key.pem (CA private key - keep secure!)"
echo ""
echo "  PostgreSQL:"
echo "    - $POSTGRES_DIR/server-cert.pem (Server certificate)"
echo "    - $POSTGRES_DIR/server-key.pem (Server private key)"
echo "    - $POSTGRES_DIR/ca-cert.pem (CA certificate for clients)"
echo ""
echo "  Redis:"
echo "    - $REDIS_DIR/redis-cert.pem (Server certificate)"
echo "    - $REDIS_DIR/redis-key.pem (Server private key)"
echo "    - $REDIS_DIR/ca-cert.pem (CA certificate for clients)"
echo ""
echo "Certificate validity: 3 years"
echo "Next steps:"
echo "  1. Create Kubernetes secrets from these certificates"
echo "  2. Mount secrets in database pods"
echo "  3. Configure PostgreSQL and Redis to use TLS"
echo "  4. Update client connection strings to require SSL"
