#!/bin/bash
# ═══════════════════════════════════════════════════════════
# 光湖语言系统 · 推送守门人部署脚本
# 目标仓库必须由服务器会话显式传入；禁止把旧广州路径当作默认值。
#
# 用法: bash deploy-pre-receive.sh <repo-hooks-dir> [reject|notify]
#   reject = 拦截含敏感信息的推送（推荐）
#   notify = 放行但发邮件通知冰朔
# ═══════════════════════════════════════════════════════════

set -e

FORGEJO_HOOK_DIR="${1:-}"
MODE="${2:-reject}"
SCRIPT_NAME="pre-receive-guard.py"
HOOK_NAME="pre-receive"

if [ -z "${FORGEJO_HOOK_DIR}" ]; then
    echo "❌ 必须传入当前 Forgejo 裸仓库的 hooks 目录。"
    echo "   例：bash deploy-pre-receive.sh /实际路径/bingshuo/fifth-domain.git/hooks reject"
    exit 2
fi

if [ ! -d "${FORGEJO_HOOK_DIR}" ]; then
    echo "❌ 目标 hooks 目录不存在：${FORGEJO_HOOK_DIR}"
    echo "   停止部署；请先通过 GLSV 会话核对当前仓库物理路径。"
    exit 2
fi

echo "🛡️  光湖推送守门人 · 部署"
echo "   模式: ${MODE}"
echo "   目标 hooks: ${FORGEJO_HOOK_DIR}"
echo ""

# 1. 不悄悄覆盖既有仓库门禁。
if [ -f "${FORGEJO_HOOK_DIR}/${HOOK_NAME}" ] && ! grep -q "光湖推送守门人 · Forgejo pre-receive 钩子包装器" "${FORGEJO_HOOK_DIR}/${HOOK_NAME}"; then
    echo "❌ 检测到已有 pre-receive Hook，未覆盖。"
    echo "   先读取并整合既有规则，再以带回滚方案的专门部署动作替换。"
    exit 3
fi

# 2. 复制服务器守门人及其导航依赖
cp pre-receive-guard.py "${FORGEJO_HOOK_DIR}/${SCRIPT_NAME}"
chmod +x "${FORGEJO_HOOK_DIR}/${SCRIPT_NAME}"
cp navigation-memory-guard.py "${FORGEJO_HOOK_DIR}/navigation-memory-guard.py"
chmod +x "${FORGEJO_HOOK_DIR}/navigation-memory-guard.py"

# 3. 创建钩子包装器（Forgejo 调用这个脚本 → 内部调 Python）。
cat > "${FORGEJO_HOOK_DIR}/${HOOK_NAME}" << 'WRAPPER'
#!/bin/bash
# 光湖推送守门人 · Forgejo pre-receive 钩子包装器
export PRE_RECEIVE_MODE="${PRE_RECEIVE_MODE:-reject}"
export FORGEJO_REPO="${FORGEJO_REPO:-unknown}"
export FORGEJO_PUSHER="${FORGEJO_PUSHER:-unknown}"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
exec python3 "${SCRIPT_DIR}/pre-receive-guard.py"
WRAPPER
chmod +x "${FORGEJO_HOOK_DIR}/${HOOK_NAME}"

# 4. 验证部署
echo ""
echo "✅ 部署完成"
echo ""
echo "   钩子位置: ${FORGEJO_HOOK_DIR}/${HOOK_NAME}"
echo "   审计脚本: ${FORGEJO_HOOK_DIR}/${SCRIPT_NAME}"
echo ""
echo "📋 下一步（在当前 GLSV 工作会话中执行）:"
echo "   # 先读取现有 Hook；如存在旧规则，先做合并、备份和回滚计划。"
echo ""
echo "   # 测试推送（在本地 clone 里试推一个含密码的文件）:"
echo "   echo 'password=test123' > test_sensitive.txt"
echo "   git add test_sensitive.txt && git commit -m 'test' && git push"
echo "   # 应该看到: 🛡️ 光湖推送守门人 · 检测到敏感信息 · 推送被拦截"
echo ""
echo "⊢ 钩子路径必须从服务器实时探测得出，旧资料只用于恢复架构，不直接覆盖现实状态。"
