#!/bin/bash

# 手动初始化 Signoz ClickHouse 数据库脚本

set -e

echo "=== 手动初始化 Signoz ClickHouse 数据库 ==="
echo

NAMESPACE="signoz"
CLICKHOUSE_POD="chi-signoz-clickhouse-cluster-0-0-0"

# 检查 ClickHouse Pod 是否运行
echo "步骤 1: 检查 ClickHouse Pod 状态..."
if ! kubectl get pod $CLICKHOUSE_POD -n $NAMESPACE &>/dev/null; then
    echo "错误: 找不到 ClickHouse Pod: $CLICKHOUSE_POD"
    exit 1
fi

if [[ $(kubectl get pod $CLICKHOUSE_POD -n $NAMESPACE -o jsonpath='{.status.phase}') != "Running" ]]; then
    echo "错误: ClickHouse Pod 未运行"
    exit 1
fi

echo "✅ ClickHouse Pod 运行正常"
echo

# 2. 创建 Signoz 数据库
echo "步骤 2: 创建 Signoz 数据库..."
kubectl exec -n $NAMESPACE $CLICKHOUSE_POD -- clickhouse-client --query="
CREATE DATABASE IF NOT EXISTS signoz_metrics;
CREATE DATABASE IF NOT EXISTS signoz_logs;
CREATE DATABASE IF NOT EXISTS signoz_traces;
"

echo "✅ 数据库创建完成"
echo

# 3. 删除现有 schema migrator 作业
echo "步骤 3: 清理现有 schema migrator 作业..."
kubectl delete job -n $NAMESPACE signoz-schema-migrator-sync &>/dev/null || true
kubectl delete job -n $NAMESPACE signoz-schema-migrator-async-init &>/dev/null || true
kubectl delete job -n $NAMESPACE signoz-schema-migrator-sync-init &>/dev/null || true

echo "✅ 旧作业清理完成"
echo

# 4. 手动运行 schema migration
echo "步骤 4: 运行 schema migration..."

# 获取 ClickHouse 连接信息
CLICKHOUSE_HOST="signoz-clickhouse"
CLICKHOUSE_PORT="9000"
CLICKHOUSE_HTTP_PORT="8123"

# 运行 schema migrator sync 作业
cat <<EOF | kubectl apply -f -
apiVersion: batch/v1
kind: Job
metadata:
  name: signoz-schema-migrator-manual-sync
  namespace: signoz
  labels:
    app.kubernetes.io/name: signoz
    app.kubernetes.io/instance: signoz
    app.kubernetes.io/component: schema-migrator
spec:
  template:
    metadata:
      labels:
        app.kubernetes.io/name: signoz
        app.kubernetes.io/instance: signoz
        app.kubernetes.io/component: schema-migrator
    spec:
      restartPolicy: OnFailure
      initContainers:
        - name: wait-for-clickhouse
          image: busybox:1.35
          command:
            - sh
            - -c
            - |
              echo "等待 ClickHouse 启动..."
              until wget --spider -q http://$CLICKHOUSE_HOST:$CLICKHOUSE_HTTP_PORT/ping; do
                echo "ClickHouse 未就绪，等待 5 秒..."
                sleep 5
              done
              echo "ClickHouse 已就绪"
      containers:
        - name: schema-migrator
          image: signoz/signoz-schema-migrator:v0.129.12
          env:
            - name: CLICKHOUSE_HOST
              value: $CLICKHOUSE_HOST
            - name: CLICKHOUSE_PORT
              value: "$CLICKHOUSE_PORT"
            - name: CLICKHOUSE_HTTP_PORT
              value: "$CLICKHOUSE_HTTP_PORT"
            - name: CLICKHOUSE_CLUSTER
              value: "cluster"
            - name: CLICKHOUSE_USER
              value: "admin"
            - name: CLICKHOUSE_PASSWORD
              value: "27ff0399-0d3a-4bd8-919d-17c2181e6fb9"
            - name: CLICKHOUSE_SECURE
              value: "false"
          args:
            - sync
            - "--cluster-name"
            - "$(CLICKHOUSE_CLUSTER)"
            - "--dsn"
            - "tcp://$(CLICKHOUSE_USER):$(CLICKHOUSE_PASSWORD)@signoz-clickhouse:$(CLICKHOUSE_PORT)"
            - "--up="
EOF

echo "✅ Schema migrator 作业已创建"
echo

# 5. 等待作业完成
echo "步骤 5: 等待 schema migration 完成..."
kubectl wait --for=condition=complete job/signoz-schema-migrator-manual-sync -n $NAMESPACE --timeout=300s

echo "✅ Schema migration 完成"
echo

# 6. 验证数据库
echo "步骤 6: 验证数据库结构..."
kubectl exec -n $NAMESPACE $CLICKHOUSE_POD -- clickhouse-client --query="SHOW DATABASES" | grep -E "(signoz_metrics|signoz_logs|signoz_traces)"

echo
echo "检查表结构:"
kubectl exec -n $NAMESPACE $CLICKHOUSE_POD -- clickhouse-client --query="SHOW TABLES FROM signoz_metrics" | head -5
kubectl exec -n $NAMESPACE $CLICKHOUSE_POD -- clickhouse-client --query="SHOW TABLES FROM signoz_logs" | head -5

echo
echo "=== 数据库初始化完成 ==="
echo
echo "验证 Signoz 服务:"
echo "1. UI 访问: http://10.206.16.5:30018"
echo "2. API 健康检查: curl http://10.206.16.5:30018/api/v1/health"
echo "3. 检查作业日志: kubectl logs -n $NAMESPACE job/signoz-schema-migrator-manual-sync"