#!/usr/bin/env bash
# ============================================================
# 第 14 章 · 演示 2：pg_restore 全场景
# ------------------------------------------------------------
# 演示：
#   ① 从 custom (-Fc) 备份并行恢复到一个临时库
#   ② 仅恢复部分表 (-t)
#   ③ 仅生成 SQL 而不执行 (-f -)
#   ④ 用 list 文件做精细化恢复 (-L toc.list)
#
# 前置：
#   - 先跑 01_pg_dump_examples.sh，会在 /tmp/pg_dump_demo 生成 learn.dump
#
# 用法：
#   bash 02_pg_restore_demo.sh
# ============================================================
set -euo pipefail

PGHOST=${PGHOST:-127.0.0.1}
PGPORT=${PGPORT:-5432}
PGUSER=${PGUSER:-postgres}
export PGHOST PGPORT PGUSER

DUMP_FILE=${DUMP_FILE:-/tmp/pg_dump_demo/learn.dump}
TARGET_DB=${TARGET_DB:-learn_pg_restore}

bar() { echo -e "\n============================================================\n$1\n============================================================"; }

if [[ ! -f "$DUMP_FILE" ]]; then
  echo "❌ 找不到 $DUMP_FILE，请先运行 01_pg_dump_examples.sh"
  exit 1
fi

bar "Step 0：准备一个全新的目标库 $TARGET_DB"
psql -d postgres -c "DROP DATABASE IF EXISTS ${TARGET_DB};"
psql -d postgres -c "CREATE DATABASE ${TARGET_DB};"

bar "Step 1：用 -j 4 并行恢复整个备份"
time pg_restore -d "$TARGET_DB" -j 4 --verbose "$DUMP_FILE" 2>&1 | tail -n 20
psql -d "$TARGET_DB" -c "
  SELECT 'users' tbl, count(*) FROM ch14_users
  UNION ALL SELECT 'products', count(*) FROM ch14_products
  UNION ALL SELECT 'orders',   count(*) FROM ch14_orders
  UNION ALL SELECT 'items',    count(*) FROM ch14_order_items;"

bar "Step 2：把 $TARGET_DB 重置后，仅恢复 ch14_users + ch14_orders 两张表"
psql -d postgres -c "DROP DATABASE ${TARGET_DB};"
psql -d postgres -c "CREATE DATABASE ${TARGET_DB};"
pg_restore -d "$TARGET_DB" -t ch14_users -t ch14_orders --verbose "$DUMP_FILE" 2>&1 | tail -n 10
psql -d "$TARGET_DB" -c "\dt"

bar "Step 3：仅生成 SQL 而不执行（-f - → 标准输出）"
pg_restore -f - "$DUMP_FILE" | head -n 25
echo "↑ 这里只是预览，可以重定向到文件做 review，例如："
echo "    pg_restore -f restore.sql $DUMP_FILE"

bar "Step 4：用 list 文件 (-L) 做精细化恢复"
TOC_FILE=/tmp/pg_dump_demo/toc.list
pg_restore -l "$DUMP_FILE" > "$TOC_FILE"
echo "原始 toc.list 内容（前 20 行）:"
head -n 20 "$TOC_FILE"

# 把 ch14_orders 那一行注释掉（前面加分号）
echo
echo "现在把所有包含 'TABLE DATA public ch14_orders' 的行注释掉，模拟「不恢复 orders 数据」"
sed -i.bak 's/^\(.*TABLE DATA public ch14_orders \)/;\1/' "$TOC_FILE"

psql -d postgres -c "DROP DATABASE ${TARGET_DB};"
psql -d postgres -c "CREATE DATABASE ${TARGET_DB};"
pg_restore -L "$TOC_FILE" -d "$TARGET_DB" --verbose "$DUMP_FILE" 2>&1 | tail -n 10

echo
echo "验证：ch14_users / ch14_products 应该有数据，ch14_orders 应该是空的（仅结构）"
psql -d "$TARGET_DB" -c "
  SELECT 'users' tbl, count(*) FROM ch14_users
  UNION ALL SELECT 'products', count(*) FROM ch14_products
  UNION ALL SELECT 'orders',   count(*) FROM ch14_orders
  UNION ALL SELECT 'items',    count(*) FROM ch14_order_items;"

bar "Step 5：清理"
psql -d postgres -c "DROP DATABASE ${TARGET_DB};"
echo "完成。"
