#!/bin/bash
# 从已确认的源库导出基础数据（只读，不修改源库）
#
# 用法：
#   SOURCE_DSN="postgres://user:pass@host:5432/db?sslmode=disable" \
#   bash scripts/manual_db_release/03_export_base_data_from_source.sh
#
# 如需导出敏感表：
#   SOURCE_DSN="..." INCLUDE_SENSITIVE=1 bash scripts/manual_db_release/03_export_base_data_from_source.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
GENERATED_DIR="${SCRIPT_DIR}/generated"
NON_SENSITIVE_DIR="${GENERATED_DIR}/non_sensitive"
SENSITIVE_DIR="${GENERATED_DIR}/sensitive"

if ! command -v pg_dump >/dev/null 2>&1; then
    echo "错误：未找到 pg_dump，请先安装 PostgreSQL 客户端工具。"
    exit 1
fi

if [ -z "${SOURCE_DSN:-}" ]; then
    echo "错误：必须设置 SOURCE_DSN。"
    exit 1
fi

mkdir -p "${NON_SENSITIVE_DIR}" "${SENSITIVE_DIR}"

non_sensitive_tables=(
    "tb_permission"
    "tb_role"
    "tb_role_permission"
    "tb_carrier"
    "tb_commission_withdrawal_setting"
    "tb_polling_config"
    "tb_polling_concurrency_config"
    "tb_polling_alert_rule"
    "tb_data_cleanup_config"
)

sensitive_tables=(
    "tb_wechat_config"
)

dump_table() {
    local table_name="$1"
    local output_file="$2"

    pg_dump \
        --data-only \
        --column-inserts \
        --no-owner \
        --no-acl \
        --quote-all-identifiers \
        --table="${table_name}" \
        "${SOURCE_DSN}" > "${output_file}"
}

echo "开始导出非敏感基础数据..."
for table_name in "${non_sensitive_tables[@]}"; do
    output_file="${NON_SENSITIVE_DIR}/${table_name}.sql"
    dump_table "${table_name}" "${output_file}"
    echo "  已导出: ${table_name}"
done

if [ "${INCLUDE_SENSITIVE:-0}" = "1" ]; then
    echo "开始导出敏感基础数据..."
    for table_name in "${sensitive_tables[@]}"; do
        output_file="${SENSITIVE_DIR}/${table_name}.sql"
        dump_table "${table_name}" "${output_file}"
        echo "  已导出: ${table_name}"
    done
else
    echo "未导出敏感表。若需导出 tb_wechat_config，请设置 INCLUDE_SENSITIVE=1。"
fi

echo ""
echo "导出完成，输出目录：${GENERATED_DIR}"
echo "注意：generated 目录下的 SQL 可能包含敏感信息，请勿直接提交到 Git。"
