#!/usr/bin/env bash
# Generate self-signed CA and service certificates for development/testing
# Usage: ./scripts/generate-dev-certs.sh [output_dir]
#
# This script creates:
# - Self-signed CA certificate and key
# - Server certificates for IAM, Chainfire, and FlareDB
#
# For production, use a proper PKI or cert-manager.

set -euo pipefail

OUTPUT_DIR="${1:-./dev-certs}"
DAYS_VALID=365

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if openssl is available
if ! command -v openssl &> /dev/null; then
    log_error "openssl not found. Please install openssl."
    exit 1
fi

log_info "Creating certificate directory: $OUTPUT_DIR"
mkdir -p "$OUTPUT_DIR"/{ca,iam,chainfire,flaredb}

# Generate CA private key
log_info "Generating CA private key..."
openssl genrsa -out "$OUTPUT_DIR/ca/ca.key" 4096

# Generate CA certificate
log_info "Generating CA certificate..."
openssl req -new -x509 -days $DAYS_VALID -key "$OUTPUT_DIR/ca/ca.key" \
    -out "$OUTPUT_DIR/ca/ca.crt" \
    -subj "/C=JP/ST=Tokyo/L=Tokyo/O=Centra Cloud/OU=Development/CN=Centra Cloud Dev CA"

log_info "CA certificate created:"
openssl x509 -in "$OUTPUT_DIR/ca/ca.crt" -noout -subject -dates

# Function to generate service certificate
generate_service_cert() {
    local service=$1
    local cn=$2
    local san=$3
    
    log_info "Generating certificate for $service..."
    
    # Generate private key
    openssl genrsa -out "$OUTPUT_DIR/$service/server.key" 2048
    
    # Generate CSR
    openssl req -new -key "$OUTPUT_DIR/$service/server.key" \
        -out "$OUTPUT_DIR/$service/server.csr" \
        -subj "/C=JP/ST=Tokyo/L=Tokyo/O=Centra Cloud/OU=Services/CN=$cn"
    
    # Create extension file for SAN
    cat > "$OUTPUT_DIR/$service/server.ext" << EXTEOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = $san
EXTEOF
    
    # Sign with CA
    openssl x509 -req -in "$OUTPUT_DIR/$service/server.csr" \
        -CA "$OUTPUT_DIR/ca/ca.crt" -CAkey "$OUTPUT_DIR/ca/ca.key" \
        -CAcreateserial -out "$OUTPUT_DIR/$service/server.crt" \
        -days $DAYS_VALID -extfile "$OUTPUT_DIR/$service/server.ext"
    
    # Cleanup CSR and extension file
    rm "$OUTPUT_DIR/$service/server.csr" "$OUTPUT_DIR/$service/server.ext"
    
    log_info "$service certificate created:"
    openssl x509 -in "$OUTPUT_DIR/$service/server.crt" -noout -subject -dates
}

# Generate service certificates
generate_service_cert "iam" "iam.service.internal" "DNS:iam.service.internal,DNS:localhost,IP:127.0.0.1"
generate_service_cert "chainfire" "chainfire.service.internal" "DNS:chainfire.service.internal,DNS:localhost,IP:127.0.0.1"
generate_service_cert "flaredb" "flaredb.service.internal" "DNS:flaredb.service.internal,DNS:localhost,IP:127.0.0.1"

# Set proper permissions
log_info "Setting file permissions..."
chmod 600 "$OUTPUT_DIR"/*/server.key "$OUTPUT_DIR/ca/ca.key"
chmod 644 "$OUTPUT_DIR"/*/server.crt "$OUTPUT_DIR/ca/ca.crt"

# Summary
log_info "Certificate generation complete!"
echo ""
echo "Certificate structure:"
echo "$OUTPUT_DIR/"
echo "├── ca/"
echo "│   ├── ca.crt                 # CA certificate (public)"
echo "│   └── ca.key                 # CA private key (protect!)"
echo "├── iam/"
echo "│   ├── server.crt"
echo "│   └── server.key"
echo "├── chainfire/"
echo "│   ├── server.crt"
echo "│   └── server.key"
echo "└── flaredb/"
echo "    ├── server.crt"
echo "    └── server.key"
echo ""
log_info "To use these certificates:"
echo "  1. Copy to /etc/centra-cloud/certs/ (or configure path in service config)"
echo "  2. Update service TOML config with paths to cert_file, key_file, ca_file"
echo "  3. Set require_client_cert=true for mTLS, false for TLS-only"
echo ""
log_warn "These are DEVELOPMENT certificates. Do NOT use in production!"
