#!/usr/bin/env bash # scripts/rollback.sh — Roll back to a previous git SHA # # Usage: bash scripts/rollback.sh set -euo pipefail REPO_DIR="${REPO_DIR:-/opt/sandbox-notebookllamalm-nextjs}" TARGET_SHA="${1:-}" RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m' info() { echo -e "${GREEN}[INFO]${NC} $*"; } warn() { echo -e "${YELLOW}[WARN]${NC} $*"; } error() { echo -e "${RED}[ERROR]${NC} $*" >&2; } if [[ -z "$TARGET_SHA" ]]; then error "Usage: bash scripts/rollback.sh " echo " Recent commits:" git -C "$REPO_DIR" log --oneline -10 exit 1 fi cd "$REPO_DIR" CURRENT_SHA=$(git rev-parse --short HEAD) info "Current SHA: ${CURRENT_SHA} → rolling back to ${TARGET_SHA}" GIT_USER="${SUDO_USER:-}" _git() { [[ -n "$GIT_USER" ]] && sudo -u "$GIT_USER" git "$@" || git "$@"; } if ! _git diff --quiet 2>/dev/null; then warn "Unstaged changes detected — stashing" _git stash -u fi _git checkout "$TARGET_SHA" info "Building images for ${TARGET_SHA}..." docker compose build --pull info "Restarting containers..." docker compose up -d --remove-orphans # Quick health check sleep 10 BACKEND_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 8 "http://localhost:9000/api/health" 2>/dev/null || echo "000") if [[ "$BACKEND_CODE" == "200" ]]; then info "Rollback to ${TARGET_SHA} succeeded (backend healthy)" else error "Rollback health check failed (backend HTTP ${BACKEND_CODE})" warn "To restore: git checkout main && docker compose build && docker compose up -d" exit 1 fi echo "" info "Rolled back to ${TARGET_SHA}. To return to main: bash scripts/deploy.sh"