#!/usr/bin/env bash # Gitea Webhook 触发的自动部署(在服务器上由 gitea_webhook.php 调用) set -euo pipefail DEPLOY_PATH="${DEPLOY_PATH:-/www/wwwroot/chufang.gynhc.com}" DEPLOY_BRANCH="${DEPLOY_BRANCH:-main}" RUN_COMPOSER="${RUN_COMPOSER:-0}" LOG_DIR="${DEPLOY_PATH}/deploy/logs" mkdir -p "$LOG_DIR" LOG_FILE="${LOG_DIR}/deploy-$(date +%Y%m%d).log" log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE" } log "=== Deploy start ===" log "DEPLOY_PATH=$DEPLOY_PATH branch=$DEPLOY_BRANCH" cd "$DEPLOY_PATH" if [[ ! -d .git ]]; then log "ERROR: not a git repository" exit 1 fi # Webhook 由 PHP(www) 触发,项目目录必须对当前用户可写 RUN_USER="$(id -un 2>/dev/null || echo unknown)" if [[ ! -w "$DEPLOY_PATH" ]]; then log "ERROR: 当前用户 ${RUN_USER} 对 ${DEPLOY_PATH} 无写权限" log "修复(root): chown -R www:www ${DEPLOY_PATH} && chmod -R u+rwX ${DEPLOY_PATH}" exit 1 fi git config --global --add safe.directory "$DEPLOY_PATH" 2>/dev/null || true git fetch origin "$DEPLOY_BRANCH" git reset --hard "origin/${DEPLOY_BRANCH}" log "Git updated to origin/${DEPLOY_BRANCH} @ $(git rev-parse --short HEAD)" if [[ "$RUN_COMPOSER" == "1" ]] && [[ -f composer.json ]]; then if command -v composer >/dev/null 2>&1; then log "Running composer install..." composer install --no-dev --optimize-autoloader --no-interaction 2>&1 | tee -a "$LOG_FILE" else log "WARN: composer not found, skip" fi fi if [[ -d runtime/cache ]]; then find runtime/cache -type f -delete 2>/dev/null || true log "Cleared runtime/cache" fi if [[ -d runtime/temp ]]; then find runtime/temp -type f -delete 2>/dev/null || true log "Cleared runtime/temp" fi log "=== Deploy done ==="