#!/bin/bash
# ═══════════════════════════════════════════════════════════
# 光湖语言系统 · 推送守门人部署脚本
# 部署到 GZ-006 (Forgejo 服务器) 和 SG-001 (备用)
#
# 用法: bash deploy-pre-receive.sh [reject|notify]
#   reject = 拦截含敏感信息的推送（推荐）
#   notify = 放行但发邮件通知冰朔
# ═══════════════════════════════════════════════════════════

set -e

MODE="${1:-reject}"
FORGEJO_HOOK_DIR="/app/gitea/hooks/pre-receive.d"
SCRIPT_NAME="pre-receive-guard.py"
HOOK_NAME="50-sensitive-guard"

echo "🛡️  光湖推送守门人 · 部署"
echo "   模式: ${MODE}"
echo "   目标: GZ-006 Forgejo"
echo ""

# 1. 创建钩子目录
mkdir -p "${FORGEJO_HOOK_DIR}"

# 2. 复制审计脚本
cp pre-receive-guard.py "${FORGEJO_HOOK_DIR}/${SCRIPT_NAME}"
chmod +x "${FORGEJO_HOOK_DIR}/${SCRIPT_NAME}"

# 3. 创建钩子包装器（Forgejo 调用这个 shell 脚本 → 内部调 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. 配置环境变量（SMTP 通知用）
ENV_FILE="/opt/zhuyuan/revive-guard/.env"
mkdir -p "$(dirname "${ENV_FILE}")"
cat > "${ENV_FILE}" << ENVEOF
# 光湖推送守门人 · 环境变量
# ⊢ 本文件不进代码仓库
PRE_RECEIVE_MODE=${MODE}
QQ_SMTP_AUTH_CODE=${QQ_SMTP_AUTH_CODE:-PLACEHOLDER_SET_ME}
SOVEREIGN_EMAIL=${SOVEREIGN_EMAIL:-ICE-GL∞_EMAIL_REDACTED}
ENVEOF
chmod 600 "${ENV_FILE}"

# 5. 验证部署
echo ""
echo "✅ 部署完成"
echo ""
echo "   钩子位置: ${FORGEJO_HOOK_DIR}/${HOOK_NAME}"
echo "   审计脚本: ${FORGEJO_HOOK_DIR}/${SCRIPT_NAME}"
echo "   环境变量: ${ENV_FILE}"
echo ""
echo "📋 下一步（手动在服务器上执行）:"
echo "   # 设置 QQ SMTP 授权码"
echo "   echo 'QQ_SMTP_AUTH_CODE=你的授权码' >> ${ENV_FILE}"
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 "   # 每个仓库都需要启用钩子（在 Forgejo 管理面板）:"
echo "   # 仓库设置 → Git 钩子 → pre-receive → 启用"
echo ""
echo "⊢ 至此，铸渊再也不会把密码推到公开仓库了"
