Files
backend/scripts/websites-agent/deploy.sh
T
Alireza HassaniandCursor f7cee26975 Track real website deploy success/failure and support master branch.
Deploy agent waits for build completion, writes status, and checks out origin/HEAD (main or master) so empty-main repos like mashinify can deploy.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 08:52:49 +03:30

87 lines
2.3 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
SLUG="${1:-}"
if [[ -z "$SLUG" ]]; then
echo "usage: deploy.sh <slug>" >&2
exit 1
fi
ROOT="/var/www/sites/$SLUG"
LOG="/var/log/websites/deploy-$SLUG.log"
STATUS="/var/log/websites/deploy-$SLUG.status.json"
exec >>"$LOG" 2>&1
write_status() {
local status="$1"
local detail="${2:-}"
detail="${detail//\\/\\\\}"
detail="${detail//\"/\\\"}"
detail="${detail//$'\n'/ }"
detail="${detail:0:500}"
printf '{"slug":"%s","status":"%s","detail":"%s","at":"%s"}\n' \
"$SLUG" \
"$status" \
"$detail" \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
>"$STATUS"
}
echo "==== $(date -u +%Y-%m-%dT%H:%M:%SZ) deploy start: $SLUG ===="
write_status "started" "Deploy running"
cleanup_fail() {
local code=$?
write_status "failed" "deploy.sh exited with code $code"
exit "$code"
}
trap cleanup_fail ERR
if [[ ! -d "$ROOT/.git" ]]; then
echo "missing site: $ROOT"
write_status "failed" "missing site directory"
exit 1
fi
cd "$ROOT"
export GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -i /root/.ssh/websites_deploy -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new}"
git fetch origin
# Prefer origin/HEAD, then main, then master (repos may use either).
BRANCH=""
if git rev-parse --verify --quiet origin/HEAD >/dev/null; then
BRANCH="$(git rev-parse --abbrev-ref origin/HEAD 2>/dev/null || true)"
BRANCH="${BRANCH#origin/}"
fi
if [[ -z "$BRANCH" || "$BRANCH" == "HEAD" ]]; then
if git rev-parse --verify --quiet origin/main >/dev/null; then
BRANCH="main"
elif git rev-parse --verify --quiet origin/master >/dev/null; then
BRANCH="master"
else
echo "could not determine default branch (tried origin/HEAD, main, master)"
write_status "failed" "no origin/main or origin/master"
exit 1
fi
fi
echo "resetting to origin/$BRANCH"
git checkout -B "$BRANCH" "origin/$BRANCH"
git reset --hard "origin/$BRANCH"
if [[ ! -f package.json ]]; then
echo "package.json missing after checkout"
write_status "failed" "package.json missing — empty or wrong branch?"
exit 1
fi
npm ci
npm run build
pm2 restart "$SLUG" --update-env || pm2 start /var/www/sites/ecosystem.config.cjs --only "$SLUG"
pm2 save || true
echo "==== $(date -u +%Y-%m-%dT%H:%M:%SZ) deploy ok: $SLUG ===="
write_status "success" "Deployed origin/$BRANCH"
trap - ERR