Files
dukang/deploy/setup-webhook.sh
T
2026-07-21 00:01:50 +08:00

88 lines
2.8 KiB
Bash

#!/usr/bin/env bash
# 在服务器上执行:安装 Webhook 自动发版
set -euo pipefail
APP_ROOT="${APP_ROOT:-/opt/dukang-haoke}"
DEPLOY_DIR="$APP_ROOT/deploy"
ENV_FILE="$DEPLOY_DIR/auto-release.env"
LOG_DIR="/var/log/dukang"
echo "==> 1. 准备目录"
mkdir -p "$LOG_DIR" /var/run
chmod +x "$DEPLOY_DIR/auto-release.sh" "$DEPLOY_DIR/setup-webhook.sh" 2>/dev/null || true
sed -i 's/\r$//' "$DEPLOY_DIR"/*.sh "$DEPLOY_DIR"/*.mjs 2>/dev/null || true
echo "==> 2. 生成 webhook 密钥(若不存在)"
if [[ ! -f "$ENV_FILE" ]]; then
SECRET="$(openssl rand -hex 24)"
cp "$DEPLOY_DIR/auto-release.env.example" "$ENV_FILE"
sed -i "s/change-me-to-a-long-random-string/$SECRET/" "$ENV_FILE"
chmod 600 "$ENV_FILE"
echo " 已创建 $ENV_FILE"
else
echo " 保留已有 $ENV_FILE"
fi
sed -i 's/\r$//' "$ENV_FILE" 2>/dev/null || true
echo "==> 3. Nginx webhook 路由"
HOOK_CONF="$DEPLOY_DIR/nginx-deploy-webhook.conf"
# 勿放在 /etc/nginx/conf.d/(会被 http 上下文直接加载)
rm -f /etc/nginx/conf.d/dukang-deploy-webhook.conf
MARKER="include $HOOK_CONF;"
for conf in \
/etc/nginx/sites-available/dukang \
/etc/nginx/conf.d/dukang-runxian.conf \
/etc/nginx/conf.d/dukang-runxian-ssl.conf
do
if [[ ! -f "$conf" ]]; then
continue
fi
# 清理旧错误 include
sed -i '\|include /etc/nginx/conf.d/dukang-deploy-webhook.conf;|d' "$conf"
if grep -q 'server_name api.dukanghaoke.com' "$conf"; then
if ! grep -qF "$MARKER" "$conf"; then
sed -i "/server_name api.dukanghaoke.com;/a\\ $MARKER" "$conf"
echo " 已 patch $conf (api.dukanghaoke.com)"
fi
elif grep -q 'server_name dkapi.runxian.top' "$conf"; then
if ! grep -qF "$MARKER" "$conf"; then
sed -i "/server_name dkapi.runxian.top;/a\\ $MARKER" "$conf"
echo " 已 patch $conf (dkapi.runxian.top)"
fi
fi
done
nginx -t
systemctl reload nginx
echo "==> 4. 启动 PM2 webhook"
cd "$APP_ROOT"
if pm2 describe dukang-deploy-webhook &>/dev/null; then
pm2 restart dukang-deploy-webhook
else
pm2 start "$DEPLOY_DIR/ecosystem.config.cjs" --only dukang-deploy-webhook
fi
pm2 save
echo "==> 5. 健康检查"
sleep 1
curl -sf http://127.0.0.1:8095/health | head -c 200
echo
SECRET="$(grep DEPLOY_WEBHOOK_SECRET "$ENV_FILE" | cut -d= -f2- | tr -d '\"')"
echo ""
echo "=========================================="
echo " Webhook 已就绪"
echo " URL: https://api.dukanghaoke.com/hooks/deploy"
echo " Secret: $SECRET"
echo " Branch: dev (refs/heads/dev)"
echo " Log: $LOG_DIR/deploy.log"
echo "=========================================="
echo ""
echo "CodeUp 配置:仓库 → 设置 → Webhooks → 添加"
echo " URL: https://api.dukanghaoke.com/hooks/deploy"
echo " Secret Token: (与上方 Secret 相同)"
echo " 触发事件: Push events"
echo " 分支过滤: dev"