#!/bin/sh
# Vault PKI Initialization Script for BreakPilot SSL Certificates
#
# This script sets up a PKI secrets engine with:
# - Root CA
# - Intermediate CA
# - Certificate issuance role for macmini hostname
# - AppRole for vault-agent authentication
#
# Usage: Run this after Vault is initialized

set -e

# Load root token from file (persistent storage mode)
if [ -z "$VAULT_TOKEN" ] && [ -f /vault/data/root-token ]; then
  export VAULT_TOKEN=$(cat /vault/data/root-token)
fi

echo "=== Vault PKI Initialization ==="
echo "Waiting for Vault to be ready..."

# Wait for Vault to be ready
until vault status > /dev/null 2>&1; do
    sleep 1
done

echo "Vault is ready. Setting up PKI..."

# Create directories
mkdir -p /vault/agent/data
mkdir -p /vault/certs

# ================================================
# Step 1: Enable PKI Secrets Engine (Root CA)
# ================================================
echo "Enabling Root CA PKI engine..."
if ! vault secrets list -format=json 2>/dev/null | grep -q '"pki/"'; then
  vault secrets enable -path=pki pki
else
  echo "PKI engine already enabled — skipping"
fi

# Set max lease TTL to 10 years for root CA
vault secrets tune -max-lease-ttl=87600h pki

# Check if Root CA already exists
if ! vault read pki/cert/ca > /dev/null 2>&1; then
    echo "Generating Root CA certificate..."
    vault write -field=certificate pki/root/generate/internal \
        common_name="BreakPilot Root CA" \
        issuer_name="root-2024" \
        ttl=87600h > /vault/certs/root_ca.crt
else
    echo "Root CA already exists, skipping generation"
fi

# Configure URLs
vault write pki/config/urls \
    issuing_certificates="http://vault:8200/v1/pki/ca" \
    crl_distribution_points="http://vault:8200/v1/pki/crl"

# ================================================
# Step 2: Enable PKI Secrets Engine (Intermediate CA)
# ================================================
echo "Enabling Intermediate CA PKI engine..."
if ! vault secrets list -format=json 2>/dev/null | grep -q '"pki_int/"'; then
  vault secrets enable -path=pki_int pki
else
  echo "Intermediate PKI engine already enabled — skipping"
fi

# Set max lease TTL to 5 years for intermediate
vault secrets tune -max-lease-ttl=43800h pki_int

# Check if Intermediate CA already exists
if ! vault read pki_int/cert/ca > /dev/null 2>&1; then
    echo "Generating Intermediate CA..."

    # Generate Intermediate CSR (using -field to get raw CSR)
    vault write -field=csr pki_int/intermediate/generate/internal \
        common_name="BreakPilot Intermediate CA" \
        issuer_name="breakpilot-intermediate" \
        > /tmp/pki_intermediate.csr

    echo "CSR generated, signing with Root CA..."

    # Sign the Intermediate with Root CA (using -field to get raw certificate)
    vault write -field=certificate pki/root/sign-intermediate \
        issuer_ref="root-2024" \
        csr=@/tmp/pki_intermediate.csr \
        format=pem_bundle \
        ttl="43800h" \
        > /tmp/intermediate.cert.pem

    echo "Importing signed intermediate certificate..."

    # Import signed intermediate certificate
    vault write pki_int/intermediate/set-signed \
        certificate=@/tmp/intermediate.cert.pem
else
    echo "Intermediate CA already exists, skipping generation"
fi

# ================================================
# Step 3: Create Role for Certificate Issuance
# ================================================
echo "Creating certificate issuance role..."

# Role for macmini certificates (internal use)
vault write pki_int/roles/breakpilot-internal \
    allowed_domains="macmini,macmini.local,localhost,breakpilot.local" \
    allow_bare_domains=true \
    allow_subdomains=true \
    allow_localhost=true \
    allow_ip_sans=true \
    max_ttl="720h" \
    ttl="168h"

# ================================================
# Step 4: Create Policy for Certificate Access
# ================================================
echo "Creating certificate policy..."

vault policy write breakpilot-pki - <<EOF
# BreakPilot PKI Policy
# Allows issuing and reading certificates

# Issue certificates
path "pki_int/issue/breakpilot-internal" {
  capabilities = ["create", "update"]
}

# Read CA certificates
path "pki/cert/ca" {
  capabilities = ["read"]
}

path "pki_int/cert/ca" {
  capabilities = ["read"]
}

# Renew own token
path "auth/token/renew-self" {
  capabilities = ["update"]
}
EOF

# ================================================
# Step 5: Create AppRole for nginx/vault-agent
# ================================================
echo "Creating AppRole for certificate management..."

if ! vault auth list -format=json 2>/dev/null | grep -q '"approle/"'; then
  vault auth enable approle
else
  echo "AppRole already enabled — skipping"
fi

# Create role for nginx certificate management
vault write auth/approle/role/breakpilot-nginx \
    token_policies="breakpilot-pki" \
    token_ttl=24h \
    token_max_ttl=168h \
    secret_id_ttl=0

# Get role-id
ROLE_ID=$(vault read -field=role_id auth/approle/role/breakpilot-nginx/role-id)

# Generate secret-id
SECRET_ID=$(vault write -field=secret_id -f auth/approle/role/breakpilot-nginx/secret-id)

echo ""
echo "=== AppRole Credentials ==="
echo "Role ID:   $ROLE_ID"
echo "Secret ID: $SECRET_ID"
echo ""

# Save credentials to file for vault-agent
echo "$ROLE_ID" > /vault/agent/data/role-id
echo "$SECRET_ID" > /vault/agent/data/secret-id
chmod 600 /vault/agent/data/role-id /vault/agent/data/secret-id

# ================================================
# Step 6: Verify PKI setup is working
# ================================================
echo "Verifying PKI setup..."

# Test that certificate issuance works (don't save, just verify)
if vault write -format=json pki_int/issue/breakpilot-internal \
    common_name="test.macmini" \
    ttl="1h" > /dev/null 2>&1; then
    echo "✓ Certificate issuance working"
else
    echo "✗ Certificate issuance failed!"
    exit 1
fi

echo ""
echo "=== PKI Initialization Complete ==="
echo ""
echo "AppRole credentials saved to /vault/agent/data/"
ls -la /vault/agent/data/
echo ""
echo "Vault-agent will generate and manage certificates automatically."
echo "Start vault-agent to begin certificate management."
