#!/usr/bin/env bash set -Eeuo pipefail APP_NAME="${APP_NAME:-pc_nuxt}" BRANCH="${BRANCH:-}" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd "$SCRIPT_DIR" log() { printf '\n[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" } require_command() { if ! command -v "$1" >/dev/null 2>&1; then log "Missing command: $1" exit 1 fi } ensure_clean_worktree() { if [ -n "$(git status --porcelain)" ]; then log "Working tree is not clean. Commit/stash/clean changes before deploy." git status --short exit 1 fi } resolve_branch() { if [ -z "$BRANCH" ]; then BRANCH="$(git rev-parse --abbrev-ref HEAD)" fi if [ "$BRANCH" = "HEAD" ]; then log "Cannot detect git branch. Please run with BRANCH=main ./restart.sh" exit 1 fi } pull_latest_code() { log "Pull latest code from origin/$BRANCH" ensure_clean_worktree git fetch origin "$BRANCH" git pull --ff-only origin "$BRANCH" } install_dependencies() { log "Install dependencies" pnpm install --frozen-lockfile } build_app() { log "Build Nuxt app" pnpm run build if [ ! -f ".output/server/index.mjs" ]; then log "Build output missing: .output/server/index.mjs" exit 1 fi } restart_app() { log "Reload app with pm2 ecosystem config" mkdir -p logs APP_NAME="$APP_NAME" pm2 startOrReload ecosystem.config.cjs --env production --update-env pm2 save >/dev/null 2>&1 || true } main() { require_command git require_command node require_command pnpm require_command pm2 resolve_branch log "Deploy start: $APP_NAME" log "Node: $(node -v 2>/dev/null || echo 'unknown')" log "pnpm: $(pnpm -v)" log "pm2: $(pm2 -v)" pull_latest_code install_dependencies build_app restart_app log "Deploy done: $APP_NAME" } main "$@"