#!/bin/sh
# One-shot: populate Infisical with oikos secrets from container env.
# Only runs if Infisical is empty (first bootstrap). Safe to re-run.
#
# Usage: ./scripts/seed-secrets.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="${REPO_DIR:-$SCRIPT_DIR/..}"
COMPOSE="docker compose -f $REPO_DIR/docker-compose.yml"

echo "=== seed-secrets: $(date) ==="

# Skip if Infisical already has secrets (avoid overwriting real values
# with dev defaults from docker-compose).
existing=$($COMPOSE exec -T api /oikos secret list 2>/dev/null | grep -c . || echo 0)
if [ "$existing" -gt 3 ]; then
    echo "SKIP: Infisical already has $existing secrets (bootstrap complete)"
    exit 0
fi

echo "Infisical has $existing secrets — seeding..."

set_count=0
skip_count=0
fail_count=0

get_container_env() {
    service="$1"
    var="$2"
    $COMPOSE exec -T "$service" printenv "$var" 2>/dev/null || true
}

seed_key() {
    key="$1"
    value="$2"
    if [ -z "$value" ]; then
        echo "SKIP: $key (empty)"
        skip_count=$((skip_count + 1))
        return
    fi
    if $COMPOSE exec -T api oikos secret set "$key" "$value" 2>/dev/null; then
        echo "SET:  $key"
        set_count=$((set_count + 1))
    else
        echo "FAIL: $key"
        fail_count=$((fail_count + 1))
    fi
}

mcp_token="$(get_container_env api OIKOS_MCP_BEARER_TOKEN)"
openrouter_key="$(get_container_env nomos OPENROUTER_API_KEY)"
webhook_hmac="$(get_container_env api WEBHOOK_HMAC_SECRET 2>/dev/null)"

api_token="$mcp_token"

seed_key "mcp_bearer-token"     "$mcp_token"
seed_key "api_token"            "$api_token"
seed_key "openrouter_api-key"   "$openrouter_key"
seed_key "webhook_hmac-secret"  "$webhook_hmac"

echo ""
echo "seed-secrets complete: $set_count set, $skip_count skipped, $fail_count failed"
