Files
evig/scripts/selfhost-deploy-evig.sh
CatoandClaude Opus 5.5 373e022b14 fix(deploy): record the live commit in /opt/evig/app/.release (#717)
/opt/evig/app is a copy, not a symlink, so nothing on the box said which
commit it serves, and a rolled-back release leaves its releases/ dir
behind — 'newest release' can name a failed deploy. Write sha=<sha12>
after a good swap, as orangecat does. forge-ops deploy-evig.sh (which
now deploys evig on merge) and fleet drift.sh read it.

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 19:15:04 +01:00

226 lines
10 KiB
Bash
Executable File

#!/usr/bin/env bash
# Deploy evig to evig.orangecat.ch (Hetzner /opt/evig/app).
set -euo pipefail
# Capture deployment metadata before loading the application's runtime env.
readonly receipt_root="${FLEET_RECEIPT_ROOT:-}"
readonly receipt_public="${FLEET_RECEIPT_PUBLIC:-}"
readonly receipt_repo="${FLEET_RECEIPT_REPO:-}"
# The box IP is defined ONCE, org-wide: the `HETZNER_IP` Actions variable
# (visibility: all), passed in by .github/workflows/deploy-selfhost.yml.
# It used to be a literal here AND in that workflow — two copies of one
# fact, so re-IPing the box meant hunting for every one of them. Override
# BOX directly for a one-off target; otherwise refuse to guess.
BOX="${BOX:-ubuntu@${HETZNER_IP:?set HETZNER_IP or BOX}}"
NAME=evig
SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REMOTE_BASE="/opt/$NAME"
REMOTE_APP="$REMOTE_BASE/app"
REMOTE_RELEASES="$REMOTE_BASE/releases"
RELEASE_SHA="${RELEASE_SHA:-$(git rev-parse --short=12 HEAD)}"
RELEASE_TIME="$(date -u +%Y%m%d%H%M%S)"
RELEASE_ID="${RELEASE_SHA}-${RELEASE_TIME}"
REMOTE_RELEASE="$REMOTE_RELEASES/$RELEASE_ID"
cd "$SRC"
[ -f "$SRC/.env.selfhost.local" ] || { echo "ERROR: missing .env.selfhost.local"; exit 1; }
set -a
# shellcheck disable=SC1091
source "$SRC/.env.selfhost.local"
set +a
echo "=== build $NAME@$RELEASE_SHA ==="
NEXT_PUBLIC_BUILD_SHA="$RELEASE_SHA" \
NEXT_PUBLIC_BUILD_TIME="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
SELF_HOST=1 \
pnpm run build
ST="$SRC/.next/standalone"
[ -d "$ST" ] || { echo "ERROR: no standalone output"; exit 1; }
# ── Apply pending DB migrations to the PROD Postgres BEFORE activating ──────
# Prod runs its own Postgres on the box. Migrations live in the repo
# and are tracked in schema_migrations. Apply any not-yet-recorded file, in
# order, each in its own transaction with ON_ERROR_STOP — so the schema is ready
# before the new code goes live. A failed migration aborts the deploy and leaves
# the current release untouched. This is the guard against prod schema drift.
# `prod_psql` pipes stdin SQL to the prod DB (host psql if present, else the
# supabase-db container); extra psql flags are passed as args.
prod_psql() {
ssh -o BatchMode=yes "$BOX" "LC_ALL=C; DB=\$(grep -E '^DATABASE_URL=' '$REMOTE_APP/.env' | cut -d= -f2- | tr -d '\"'); if command -v psql >/dev/null 2>&1; then psql \"\$DB\" $* ; else docker exec -i -e LC_ALL=C supabase-db psql -U postgres -d revampit $* ; fi"
}
# ── Ensure ffmpeg on the box ────────────────────────────────────────────────
# Protocol audio above Groq's 25 MB upload cap is transcoded + segmented
# server-side (src/lib/transcription/segment-audio.ts); that needs ffmpeg.
# Idempotent: installs once, no-ops on every later deploy.
echo "=== ensure ffmpeg on box (chunked audio transcription) ==="
ssh -o BatchMode=yes "$BOX" 'command -v ffmpeg >/dev/null 2>&1 || { sudo DEBIAN_FRONTEND=noninteractive apt-get -qq update && sudo DEBIAN_FRONTEND=noninteractive apt-get -qq install -y --no-install-recommends ffmpeg; }'
echo "=== apply pending migrations → prod DB ==="
# Fail CLOSED when the applied-migrations state cannot be read. With `|| true`
# a transient ssh/psql failure produced an EMPTY list, which does not mean
# "nothing is applied" — it means "we could not look". The loop below treats
# every unlisted file as pending, so an unreadable state would have re-applied
# all ~150 migrations against the live production database.
if ! applied_list="$(printf '' | prod_psql "-tAc 'SELECT filename FROM schema_migrations'")"; then
echo "ERROR: could not read schema_migrations on prod — refusing to guess which"
echo " migrations are pending (an empty answer would re-apply all of them)."
exit 1
fi
# Same order and same superseded-duplicate list as the CI replay and the local
# runner. This path used a bare glob (lexicographic), which orders the 005*
# duplicates the OPPOSITE way from `sort -V` — so the order production would use
# during a disaster-recovery rebuild was the one order CI never exercised.
# shellcheck source=scripts/db/migration-order.sh
source "$SRC/scripts/db/migration-order.sh"
for mig in $(migration_files); do
fname="$(basename "$mig")"
grep -qxF "$fname" <<<"$applied_list" && continue
echo " → applying $fname"
if ! { echo "BEGIN;"; cat "$mig"; printf "INSERT INTO schema_migrations(filename) VALUES('%s') ON CONFLICT DO NOTHING; COMMIT;\n" "$fname"; } \
| prod_psql "-v ON_ERROR_STOP=1 -q"; then
echo "ERROR: migration $fname failed — aborting deploy (current release stays live)"
exit 1
fi
done
echo " migrations up to date"
STAGE="$(mktemp -d)"
trap 'rm -rf "$STAGE"' EXIT
cp -r "$ST"/. "$STAGE/"
NEST="$(cd "$STAGE" && find . -maxdepth 4 -name server.js -not -path '*node_modules*' | head -1 | xargs dirname)"
mkdir -p "$STAGE/$NEST/.next/static"
cp -a "$SRC/.next/static/." "$STAGE/$NEST/.next/static/"
[ -d "$SRC/public" ] && cp -a "$SRC/public/." "$STAGE/$NEST/public/"
receipt_file="$STAGE/$NEST/public/.well-known/fleet-release.json"
rm -f "$receipt_file"
if [ "$receipt_public" = true ]; then
test -f "$receipt_root/scripts/ci/release-receipt.mjs"
node "$receipt_root/scripts/ci/release-receipt.mjs" --public \
--root "$SRC" --dir "$SRC" --repo "$receipt_repo" --output "$receipt_file"
fi
if [ -d "$SRC/node_modules/@swc/helpers/esm" ]; then
mkdir -p "$STAGE/$NEST/node_modules/@swc/helpers"
cp -a "$SRC/node_modules/@swc/helpers/esm" "$STAGE/$NEST/node_modules/@swc/helpers/"
fi
# ── shiki top-level link (bip-kit long-form highlighting) ───────────────────
# Next auto-externalizes shiki, and bip-kit's ArticleBody loads it with plain
# Node resolution from the server chunk at runtime. Output tracing copies the
# .pnpm store entries into standalone node_modules/.pnpm but does not always
# emit the top-level node_modules/shiki symlink — on the box (no outer
# node_modules to leak from) the import then finds nothing and blog code
# blocks silently render as the un-highlighted mono fallback while dev shows
# them highlighted. Same trap and same fix as Loki #513 and orangecat's
# deploy-selfhost.sh: what the tracer can't see, the assemble step supplies.
# Version-agnostic; no-op when the link already exists.
for NM in "$STAGE/node_modules" "$STAGE/$NEST/node_modules"; do
SHIKI_STORE_ENTRY="$(ls "$NM/.pnpm" 2>/dev/null | grep -E '^shiki@' | head -1 || true)"
if [ -n "$SHIKI_STORE_ENTRY" ] && [ ! -e "$NM/shiki" ]; then
ln -s ".pnpm/$SHIKI_STORE_ENTRY/node_modules/shiki" "$NM/shiki"
echo "→ deploy: linked ${NM#"$STAGE/"}/shiki -> .pnpm/$SHIKI_STORE_ENTRY"
fi
done
echo "=== rsync release → $REMOTE_RELEASE ==="
ssh -o BatchMode=yes "$BOX" "sudo mkdir -p '$REMOTE_RELEASE' && sudo chown \"\$(id -u):\$(id -g)\" '$REMOTE_RELEASES' && sudo chown -R \"\$(id -u):\$(id -g)\" '$REMOTE_RELEASE'"
rsync -az --delete --partial \
-e "ssh -o BatchMode=yes -o ServerAliveInterval=15" \
--exclude '.env' --exclude 'launch.sh' \
"$STAGE"/ "$BOX:$REMOTE_RELEASE/"
echo "=== activate release $RELEASE_ID ==="
result=$(
ssh -o BatchMode=yes "$BOX" \
"NAME='$NAME' APP='$REMOTE_APP' RELEASE='$REMOTE_RELEASE' RELEASES='$REMOTE_RELEASES' bash -s" <<'REMOTE'
set -euo pipefail
NEXT="${APP}.next"
PREV="${APP}.previous"
sudo rm -rf "$NEXT"
sudo cp -a "$RELEASE" "$NEXT"
sudo rm -rf "$PREV"
if sudo test -f "$APP/.env"; then
sudo cp -a "$APP/.env" "$NEXT/.env"
fi
if sudo test -f "$APP/launch.sh"; then
sudo cp -a "$APP/launch.sh" "$NEXT/launch.sh"
fi
# Durable user uploads: keep them in ONE stable directory outside the release
# dirs and symlink it into each release's public/uploads, so every deploy shares
# the same store (served by Next at /uploads/*). Free, self-hosted image
# storage — set S3_* later to move to object storage without code changes.
PERSIST_UPLOADS="$(dirname "$APP")/uploads"
sudo mkdir -p "$PERSIST_UPLOADS"
# One-time fold-in: if the current app had real (non-symlink) uploads, move them
# into the persistent store before we switch to the symlink.
if sudo test -d "$APP/public/uploads" && ! sudo test -L "$APP/public/uploads"; then
sudo cp -an "$APP/public/uploads/." "$PERSIST_UPLOADS/" 2>/dev/null || true
fi
sudo mkdir -p "$NEXT/public"
sudo rm -rf "$NEXT/public/uploads"
sudo ln -sfn "$PERSIST_UPLOADS" "$NEXT/public/uploads"
if sudo test -e "$APP" || sudo test -L "$APP"; then
sudo mv "$APP" "$PREV"
fi
sudo mv "$NEXT" "$APP"
set +e
sudo systemctl restart "${NAME}-app"
sleep 5
status="$(systemctl is-active "${NAME}-app")"
code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 http://localhost:4004/api/health)"
# Also gate on a real PAGE render — /api/health is an API route and stays 200
# even when SSR crashes site-wide (e.g. a provider throwing during render).
page="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 http://localhost:4004/)"
set -e
if [ "$status" != "active" ] || [ "$code" -lt 200 ] || [ "$code" -ge 400 ] || [ "$page" -lt 200 ] || [ "$page" -ge 400 ]; then
echo "rollback status=$status http=$code page=$page"
sudo rm -rf "$APP"
if sudo test -e "$PREV" || sudo test -L "$PREV"; then
sudo mv "$PREV" "$APP"
sudo systemctl restart "${NAME}-app" || true
fi
exit 1
fi
sudo rm -rf "$PREV"
# Record what is live. /opt/evig/app is a copy, not a symlink, so nothing else
# on the box says which commit it serves — and a rolled-back release leaves its
# releases/ dir behind, so "newest release" can name a deploy that failed.
# forge-ops deploy-evig.sh and fleet drift.sh read this line (as for orangecat).
echo "sha=$(basename "$RELEASE" | cut -d- -f1)" | sudo tee "$APP/.release" >/dev/null
find "$RELEASES" -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p\n' \
| sort -rn \
| tail -n +6 \
| cut -d' ' -f2- \
| xargs -r sudo rm -rf
echo "status=$status http=$code page=$page"
REMOTE
)
echo "RESULT $NAME@$RELEASE_SHA: $result"
if [ "$receipt_public" = true ]; then
node "$receipt_root/scripts/ci/verify-live-release-receipt.mjs" \
--url https://evig.orangecat.ch/.well-known/fleet-release.json --expected "$receipt_file"
fi
echo "Done: https://evig.orangecat.ch/"