#!/bin/sh
set -e

# etcdctl 基础参数
ETCDCTL_API=3
export ETCDCTL_API

# 默认连接地址（改成你的 etcd 集群地址）
ENDPOINTS="http://127.0.0.1:2379"

# 管理员账号密码
ROOT_USER="etcd"
ROOT_PASS="etcd@2020"

# Patroni 专用账号
PATRONI_USER="patroni"
PATRONI_PASS="patroni@2020"
PATRONI_ROLE="patroni-role"
PATRONI_PREFIX="/service/"

# 检查 root 是否存在
if etcdctl --endpoints=$ENDPOINTS user list | grep -q "$ROOT_USER"; then
  echo "✅ etcd 用户已初始化，跳过创建"
else
  echo "🚀 初始化 etcd 用户和角色..."

  # 创建 root 用户和角色
  etcdctl --endpoints=$ENDPOINTS user add "${ROOT_USER}:${ROOT_PASS}"
  etcdctl --endpoints=$ENDPOINTS role add root
  etcdctl --endpoints=$ENDPOINTS user grant-role $ROOT_USER root

  # 创建 Patroni 专用用户
  etcdctl --endpoints=$ENDPOINTS role add $PATRONI_ROLE
  etcdctl --endpoints=$ENDPOINTS role grant-permission $PATRONI_ROLE readwrite "${PATRONI_PREFIX}" --prefix
  etcdctl --endpoints=$ENDPOINTS user add "${PATRONI_USER}:${PATRONI_PASS}"
  etcdctl --endpoints=$ENDPOINTS user grant-role $PATRONI_USER $PATRONI_ROLE

  # 启用认证
  etcdctl --endpoints=$ENDPOINTS auth enable || true

  echo "✅ etcd 用户和角色初始化完成"
fi
