#!/bin/bash
set -e

# DashCA Certificate Generation Script
# This script generates all required certificate formats

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CA_DIR="$(dirname "$SCRIPT_DIR")"
CADDY_CERT_DIR="C:/caddy/certs/pki/authorities/local"

echo "======================================"
echo "DashCA Certificate Format Generator"
echo "======================================"
echo ""

# Step 1: Copy certificates from Caddy
echo "[1/4] Copying certificates from Caddy PKI..."
if [ ! -f "$CADDY_CERT_DIR/root.crt" ]; then
  echo "ERROR: Root certificate not found at $CADDY_CERT_DIR/root.crt"
  exit 1
fi

cp "$CADDY_CERT_DIR/root.crt" "$CA_DIR/"
cp "$CADDY_CERT_DIR/intermediate.crt" "$CA_DIR/" 2>/dev/null || echo "  (Intermediate certificate not found, skipping)"
echo "  ✓ Certificates copied"

# Step 2: Generate DER format
echo "[2/4] Generating DER format..."
openssl x509 -in "$CA_DIR/root.crt" -outform DER -out "$CA_DIR/root.der"
echo "  ✓ DER format generated: root.der"

# Step 3: Generate certificate info JSON
echo "[3/4] Extracting certificate metadata..."
node "$SCRIPT_DIR/generate-cert-info.js"

# Step 4: Generate Apple mobileconfig
echo "[4/4] Generating Apple mobile configuration profile..."
node "$SCRIPT_DIR/generate-mobileconfig.js"

echo ""
echo "======================================"
echo "✓ All certificate formats generated!"
echo "======================================"
echo ""
echo "Files created in: $CA_DIR"
ls -lh "$CA_DIR"/*.{crt,der,mobileconfig,json} 2>/dev/null || echo "Files created successfully"
echo ""
echo "To deploy to production:"
echo "  cp -r $CA_DIR/* C:/caddy/sites/ca/"
echo ""
