#!/usr/bin/env bash
# Bootstrap CouchDB для Obsidian Self-hosted LiveSync.
#
# Запускается ОДИН РАЗ после первого `docker compose up -d couchdb`.
# Идемпотентен — повторный запуск безопасен.
#
# Что делает:
#   1. Конвертирует single-node setup в "single-node configured" (требование CouchDB 3.x)
#   2. Включает CORS (нужно для Obsidian мобильного / browser-client)
#   3. Увеличивает max_http_request_size до 4 GiB (для крупных attachments)
#   4. Создаёт database `gendesign-vault` для самого vault
#   5. Создаёт database `_users` (системная, для multi-user в будущем)
#
# Использование:
#   COUCHDB_PASSWORD=xxx ./scripts/setup-couchdb.sh
#   # или на VPS:
#   docker compose exec couchdb bash -c 'curl ...'  # ручной путь
#
# Требует: curl. Запускать с хоста VPS (couchdb должен быть на 127.0.0.1:5984).

set -euo pipefail

COUCHDB_HOST="${COUCHDB_HOST:-http://localhost:5984}"
COUCHDB_USER="${COUCHDB_USER:-obsidian}"
COUCHDB_PASSWORD="${COUCHDB_PASSWORD:?COUCHDB_PASSWORD env var is required}"
VAULT_DB="${VAULT_DB:-gendesign-vault}"

AUTH="-u ${COUCHDB_USER}:${COUCHDB_PASSWORD}"

echo "=== 0. Wait for CouchDB ready ==="
for i in $(seq 1 30); do
    if curl -fsS "${COUCHDB_HOST}/_up" >/dev/null 2>&1; then
        echo "   CouchDB up after ${i}s"
        break
    fi
    sleep 1
done

echo "=== 1. Convert to 'configured single-node' (idempotent) ==="
curl -fsS ${AUTH} -X POST "${COUCHDB_HOST}/_cluster_setup" \
    -H "Content-Type: application/json" \
    -d '{"action":"enable_single_node","bind_address":"0.0.0.0","username":"'"${COUCHDB_USER}"'","password":"'"${COUCHDB_PASSWORD}"'"}' \
    || echo "   (уже configured, OK)"

echo "=== 2. Системные базы ==="
for db in _users _replicator _global_changes; do
    curl -fsS ${AUTH} -X PUT "${COUCHDB_HOST}/${db}" 2>&1 \
        | grep -q '"ok":true\|"file_exists"' && echo "   ${db}: OK"
done

echo "=== 3. Vault database '${VAULT_DB}' ==="
curl -fsS ${AUTH} -X PUT "${COUCHDB_HOST}/${VAULT_DB}" 2>&1 \
    | grep -q '"ok":true\|"file_exists"' && echo "   ${VAULT_DB}: OK"

echo "=== 4. CORS (для мобильных клиентов) ==="
cors_settings=(
    "httpd/enable_cors true"
    "cors/origins app://obsidian.md,capacitor://localhost,http://localhost"
    "cors/credentials true"
    "cors/methods GET,PUT,POST,HEAD,DELETE"
    "cors/headers accept,authorization,content-type,origin,referer,x-csrf-token"
)
for kv in "${cors_settings[@]}"; do
    key="${kv%% *}"
    value="${kv#* }"
    curl -fsS ${AUTH} -X PUT \
        "${COUCHDB_HOST}/_node/_local/_config/${key}" \
        -H "Content-Type: application/json" \
        -d "\"${value}\"" >/dev/null
    echo "   ${key} = ${value}"
done

echo "=== 5. Размер запросов / chunks (для больших документов LiveSync) ==="
curl -fsS ${AUTH} -X PUT \
    "${COUCHDB_HOST}/_node/_local/_config/chttpd/max_http_request_size" \
    -H "Content-Type: application/json" \
    -d '"4294967296"' >/dev/null
echo "   chttpd/max_http_request_size = 4 GiB"

curl -fsS ${AUTH} -X PUT \
    "${COUCHDB_HOST}/_node/_local/_config/couchdb/max_document_size" \
    -H "Content-Type: application/json" \
    -d '"50000000"' >/dev/null
echo "   couchdb/max_document_size = 50 MB"

echo "=== 6. Auth settings (CouchDB 3.x требует session timeout для LiveSync) ==="
curl -fsS ${AUTH} -X PUT \
    "${COUCHDB_HOST}/_node/_local/_config/chttpd_auth/require_valid_user" \
    -H "Content-Type: application/json" \
    -d '"true"' >/dev/null
curl -fsS ${AUTH} -X PUT \
    "${COUCHDB_HOST}/_node/_local/_config/chttpd_auth/timeout" \
    -H "Content-Type: application/json" \
    -d '"7200"' >/dev/null
echo "   chttpd_auth: require_valid_user=true, timeout=7200s"

echo ""
echo "=== DONE ==="
echo "CouchDB готова к Self-hosted LiveSync."
echo ""
echo "Клиенту Obsidian → Settings → Self-hosted LiveSync → Remote DB:"
echo "  URL:      https://obsidian.gendsgn.ru"
echo "  Database: ${VAULT_DB}"
echo "  User:     ${COUCHDB_USER}"
echo "  Password: <COUCHDB_PASSWORD>"
echo ""
echo "Дальше: 'Test Database Connection' → 'Apply Settings' → 'Replicate Now'."
