#!/usr/bin/env bash
# 交互式创建 4 个 podman secret，供 Quadlet 单元引用
# 用法：bash create-secrets.sh

set -euo pipefail

if ! command -v podman >/dev/null 2>&1; then
    echo "未检测到 podman，请先安装" >&2
    exit 1
fi

create_secret() {
    local name=$1
    local prompt=$2
    local default_cmd=${3:-}

    if podman secret exists "$name" 2>/dev/null; then
        read -rp "secret [$name] 已存在，是否替换？(y/N): " ans
        if [[ "${ans,,}" != "y" ]]; then
            echo "  跳过 $name"
            return
        fi
        podman secret rm "$name" >/dev/null
    fi

    local value
    if [[ -n "$default_cmd" ]]; then
        read -rp "$prompt（直接回车自动生成）: " -s value
        echo
        if [[ -z "$value" ]]; then
            value=$(eval "$default_cmd")
            echo "  已自动生成"
        fi
    else
        read -rp "$prompt: " -s value
        echo
        if [[ -z "$value" ]]; then
            echo "  值不能为空" >&2
            exit 1
        fi
    fi

    printf '%s' "$value" | podman secret create "$name" -
    echo "  ✓ 创建 $name"
}

echo "=== 创建 datahub podman secrets ==="
echo

create_secret datahub-pg-password        "PostgreSQL datahub 用户密码"
create_secret datahub-rabbitmq-password  "RabbitMQ user 用户密码"
create_secret datahub-jwt-secret         "JWT 签名 secret" "openssl rand -hex 32"
create_secret datahub-tools-token        "TOOLS_TOKEN（外部 store-api 鉴权 token）"

echo
echo "完成。当前 secrets："
podman secret ls
