#!/bin/sh
# Vault Init + Unseal Script for persistent (file) storage
set -e

export VAULT_ADDR="http://vault:8200"
KEYS_FILE="/vault/data/init-keys.json"
INIT_MARKER="/vault/data/.init-complete"

echo "=== Vault Init/Unseal ==="
echo "Waiting for Vault to be ready..."

until vault status >/dev/null 2>&1 || [ $? -eq 2 ]; do
  sleep 1
done

INITIALIZED=$(vault status -format=json 2>/dev/null | grep '"initialized"' | tr -d ' ,"' | cut -d: -f2)

if [ "$INITIALIZED" = "false" ]; then
  echo "First start — initializing Vault..."
  vault operator init -key-shares=1 -key-threshold=1 -format=json > "$KEYS_FILE"
  chmod 600 "$KEYS_FILE"
  echo "Vault initialized. Keys saved."
fi

SEALED=$(vault status -format=json 2>/dev/null | grep '"sealed"' | tr -d ' ,"' | cut -d: -f2)

if [ "$SEALED" = "true" ]; then
  echo "Unsealing Vault..."
  UNSEAL_KEY=$(grep -A1 unseal_keys_b64 "$KEYS_FILE" | tail -1 | tr -d ' ",')
  echo "Using key: ${UNSEAL_KEY}"
  vault operator unseal "$UNSEAL_KEY" > /dev/null
  echo "Vault unsealed."
fi

# Extract root token
ROOT_TOKEN=$(grep root_token "$KEYS_FILE" | tr -d ' ",' | cut -d: -f2)
export VAULT_TOKEN="$ROOT_TOKEN"
echo "$ROOT_TOKEN" > /vault/data/root-token
chmod 600 /vault/data/root-token

echo "=== Vault ready (persistent file storage) ==="

# Skip PKI + secrets init if already completed (prevents repeated mount-enable errors)
if [ -f "$INIT_MARKER" ]; then
  echo "PKI + secrets already initialized (marker: $INIT_MARKER). Skipping."
  exit 0
fi

# Run PKI init
if [ -f /vault/scripts/init-pki.sh ]; then
  echo "Running PKI initialization..."
  sh /vault/scripts/init-pki.sh
fi

# Run secrets init
if [ -f /vault/scripts/init-secrets.sh ]; then
  echo "Running secrets initialization..."
  sh /vault/scripts/init-secrets.sh
fi

# Mark initialization as complete
touch "$INIT_MARKER"
echo "Init marker written: $INIT_MARKER"
