3 Commits
Author SHA1 Message Date
joshua e8853cf0c8 Merge branch 'feat/crosscode-script' 2026-11-12 19:27:57 +02:00
joshuaandClaude Opus 5.5 c442fe0d42 crosscode script: deploy, status, install, adopt (Events 2.2.0, plan §4-5)
One script for installing, updating and moving church installs, replacing
hope-events' scripts/deploy.sh and install.sh:

- deploy <church> [events] / --every-church, with --version, --main, --check
  and --allow-local-changes: checks every product first (files changed by
  hand, Node, release requirements from WHATS-NEW.md headings), then each
  product in order with backup, checkout, install, migrate, build, PM2 reload
  and a /health version check; a failure rolls that product back and stops.
- status [<church>]: checked-out and latest release, /health, and the old
  folder kept after adopt.
- install <church> --products events --domain <address>: a new church under
  /var/www/sites/<church>, writing church.env.
- adopt <church> --events-dir <old> builds the monorepo checkout next to the
  running install and switches PM2 over; adopt --undo goes back to it.

Product hooks live in scripts/products/events.sh. shellcheck (lint:scripts)
and 47 bats tests (test:scripts) are part of npm run check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:17:06 +02:00
joshua f174285711 Merge branch 'move/events' (Cross Events into apps/events) 2026-11-12 17:34:45 +02:00
16 changed files with 3111 additions and 7 deletions
+26
View File
@@ -181,6 +181,32 @@ Secrets stay in each product's own `.env`, never in `church.env`.
| `adopt <church> --undo` | Yes (decision 26): goes back to the old folder and the 2.1.x it ran, within the days the old folder is kept |
| `add <church> <product>` | **Later** (phase 3), when there's a second product to add |
**Built 2026-11-12** (branch `feat/crosscode-script`), as above, with these details settled while
writing it:
- **Run as root.** `church.env` is root-only (mode 600), so every command needs root; each app's
commands (git, npm, Prisma, PM2) run as its app user through `sudo -u`.
- `church.env` is read as data, never sourced: only `CHURCH`, `PRODUCTS`, `ADDRESS` and
`<PRODUCT>_*` keys are taken.
- `--allow-local-changes` replaces `ALLOW_LOCAL_CHANGES=1` (the variable still works). `--check`
never passes with changes.
- "Latest" only counts plain `events@x.y.z` tags, so test tags such as `events@2.2.0-test` are
only ever deployed with `--version`.
- `--every-church` stops at the first church that fails (its products roll back as usual), and
names the churches it didn't reach.
- `install`: the app user defaults to `cc-<church>`, PM2 names to `<church>-events-backend` /
`-frontend`, the database to `<church>_events`, and ports to the first free ones from 5000
(API) and 3000 (web), counting every church's `church.env` and anything listening.
- `adopt` writes `church.env` only once the switch has worked, and refuses to start if nginx
refers to the old folder by path (it gets renamed). It also records `EVENTS_OLD_DIR`,
`EVENTS_OLD_REF` and `EVENTS_ADOPTED_AT` for `--undo` and `status`.
- `adopt --undo` refuses if the new checkout has migrations the old release doesn't have, and
moves `/var/www/sites/<church>` aside to `.undone-<church>-<time>` (not deleted), so `adopt`
can be run again.
- Tests: `npm run lint:scripts` (shellcheck) and `npm run test:scripts` (bats: 47 tests,
including deploys against a local git origin with stub hooks for the checks, requirements,
order, rollback and `--every-church`). Both are part of `npm run check`.
**Requirement check** (decision 24): before anything is touched, read the target version's
heading in `apps/<product>/WHATS-NEW.md`. Refuse the deploy if a `— requires <product> <version>`
isn't met by the installed sibling or by this same run. Nothing in 2.2.0 requires anything, but
+1 -1
View File
@@ -25,7 +25,7 @@ for each phase. They moved here from `hope-events/docs/` on 2026-11-05.
|-------|------|-------|
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04 (`contracts@1.0.0`, `contracts@1.1.0`). Not published to a registry (decision 22): the Hub gets a packed release committed to its repo |
| 1 | Hub 2.0.0 | **Released** 2026-11-05 (`events-hub` `v2.0.0`; `docs/HUB-2.0-PLAN.md` there). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first). crosscode-site's address prices are merged, **not deployed yet** |
| 1b | Cross Events 2.2.0: moves here as `apps/events`, `crosscode` script | **In progress.** Planned in [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). **Steps 1–3 done 2026-11-12** (merged into `main`): history merged in under `apps/events` (from `hope-events` `e6c9670`), workspaces and one root lockfile with versions pinned to 2.1.1, same test results as 2.1.1 (711 backend tests, typecheck, both builds). **Still to do:** the `crosscode` script and `adopt` (§4–5), VM testing (§6), the version bump and `events@2.2.0` tag, adopting each install, archiving `hope-events` (§7). Until then servers keep deploying from `hope-events` `v2.1.1`, and **Events work happens here** (`hope-events` is frozen; a hotfix there as 2.1.2 is cherry-picked into `apps/events`) |
| 1b | Cross Events 2.2.0: moves here as `apps/events`, `crosscode` script | **In progress.** Planned in [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). **Steps 1–3 done 2026-11-12** (merged into `main`): history merged in under `apps/events` (from `hope-events` `e6c9670`), workspaces and one root lockfile with versions pinned to 2.1.1, same test results as 2.1.1 (711 backend tests, typecheck, both builds). **The `crosscode` script and `adopt` (§4–5) are written** (branch `feat/crosscode-script`, 2026-11-12; shellcheck and 47 bats tests pass, not yet run on a server). **Still to do:** VM testing (§6), the version bump and `events@2.2.0` tag, adopting each install, archiving `hope-events` (§7). Until then servers keep deploying from `hope-events` `v2.1.1`, and **Events work happens here** (`hope-events` is frozen; a hotfix there as 2.1.2 is cherry-picked into `apps/events`) |
| 1c | Cross Events 2.3.0: authenticator app 2FA (TOTP + recovery codes) | Not started (`TwoFactorMethod` enum in Events' `prisma/schema.prisma`) |
| 1d | Agent 1.0.0 + Hub 2.1.0 (+ contracts 1.2.0): server agent, installs / scheduled updates / uninstalls from the Hub, server stats | **Planned** 2026-11-12 in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) (ROADMAP decisions 27–37). Starts after 1b; can run alongside 1c |
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | Not started. Events keeps speaking protocol 1 until then |
+1056 -5
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -13,9 +13,11 @@
"scripts": {
"build": "npm run build --workspaces --if-present",
"test": "npm test --workspaces --if-present",
"test:scripts": "bats scripts/tests",
"typecheck": "npm run typecheck --workspaces --if-present",
"lint": "eslint .",
"check": "npm run lint && npm run typecheck && npm test && npm run build"
"lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh",
"check": "npm run lint && npm run lint:scripts && npm run typecheck && npm test && npm run test:scripts && npm run build"
},
"engines": {
"node": ">=20"
@@ -26,9 +28,11 @@
"@playwright/test": "^1.64.0",
"@types/jest": "^30.0.0",
"@types/node": "^20.19.43",
"bats": "^1.13.0",
"concurrently": "^9.2.1",
"eslint": "^10.13.0",
"jest": "^30.5.2",
"shellcheck": "^4.1.0",
"ts-jest": "^29.4.15",
"tsup": "^9.0.0",
"typescript": "^5.9.3",
+3
View File
@@ -0,0 +1,3 @@
# shellcheck settings for the crosscode script (npm run lint:scripts).
source-path=SCRIPTDIR
external-sources=true
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
# crosscode: installs, updates and moves church installs on this server (ROADMAP-v3 §8,
# docs/EVENTS-2.2-PLAN.md §4). `crosscode help` lists the commands.
#
# On a server this is a checkout of crosscode-platform's main in /opt/crosscode/tools, linked as
# /usr/local/bin/crosscode. Every run first updates that checkout (git pull --ff-only), then runs
# from a copy, so a checkout never changes the script while it runs.
#
# Environment: CROSSCODE_SITES (default /var/www/sites), CROSSCODE_REPO (the monorepo's git URL),
# CROSSCODE_TOOLS_DIR (default /opt/crosscode/tools), CROSSCODE_NO_UPDATE=1 (skip the update).
set -Eeuo pipefail
CROSSCODE_TOOLS_DIR="${CROSSCODE_TOOLS_DIR:-/opt/crosscode/tools}"
if [ -z "${CROSSCODE_HOME:-}" ]; then
src="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
root="$(cd "$src/.." && pwd)"
if [ "${CROSSCODE_NO_UPDATE:-}" != 1 ] && [ "$root" = "$CROSSCODE_TOOLS_DIR" ] && [ -d "$root/.git" ]; then
git -C "$root" pull --ff-only --quiet ||
printf '!!> Couldn'"'"'t update %s; running the version that is there.\n' "$root" >&2
fi
copy="$(mktemp -d /tmp/crosscode.XXXXXX)"
cp -R "$src/." "$copy/"
CROSSCODE_HOME="$copy" CROSSCODE_FROM="$root" exec bash "$copy/crosscode" "$@"
fi
# Running from the copy: remove it afterwards (only ever a mktemp folder, never a checkout).
if [[ "$CROSSCODE_HOME" == /tmp/crosscode.* ]]; then
trap 'rm -rf "$CROSSCODE_HOME"' EXIT
fi
# shellcheck source=lib/common.sh
source "$CROSSCODE_HOME/lib/common.sh"
# shellcheck source=lib/deploy.sh
source "$CROSSCODE_HOME/lib/deploy.sh"
# shellcheck source=lib/status.sh
source "$CROSSCODE_HOME/lib/status.sh"
# shellcheck source=lib/install.sh
source "$CROSSCODE_HOME/lib/install.sh"
# shellcheck source=lib/adopt.sh
source "$CROSSCODE_HOME/lib/adopt.sh"
usage() {
cat <<EOF
crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" rev-parse --short HEAD 2>/dev/null || echo 'unknown version'))
crosscode deploy <church> [events] [website] [app] update Accounts and the products named
crosscode deploy --every-church [events] … the same, for every church here
crosscode deploy <church> … --check only the checks; changes nothing
crosscode status [<church>] versions, latest releases, health
crosscode install <church> --products events --domain <address> a new church
crosscode adopt <church> --events-dir <old folder> move an existing Cross Events install here
crosscode adopt <church> --undo go back to the old folder (within 14 days)
crosscode help [<command>] this, or a command's options
Churches live in $CROSSCODE_SITES/<church>/ (church.env, one checkout per product).
EOF
}
command="${1:-help}"
[ $# -gt 0 ] && shift
case "$command" in
deploy) cmd_deploy "$@" ;;
status) cmd_status "$@" ;;
install) cmd_install "$@" ;;
adopt) cmd_adopt "$@" ;;
add) die "\`crosscode add\` comes with the second product (phase 3)." ;;
help|-h|--help)
case "${1:-}" in
deploy) deploy_usage ;;
status) status_usage ;;
install) install_usage ;;
adopt) adopt_usage ;;
*) usage ;;
esac ;;
*) usage; die "Unknown command \"$command\"." ;;
esac
+289
View File
@@ -0,0 +1,289 @@
# shellcheck shell=bash
# crosscode adopt: moves an existing Cross Events install (a hope-events checkout at v2.1.x) onto
# the monorepo, into /var/www/sites/<church>/events (EVENTS-2.2-PLAN §5, decisions 25 and 26).
# The new checkout is built next to the running install, then PM2 switches over (seconds of
# downtime). The old folder isn't changed, so a failed switch just starts it again.
ADOPT_KEEP_DAYS=14
ADOPT_SUFFIX=".pre-2.2.0"
adopt_usage() {
cat <<'EOF'
crosscode adopt <church> --events-dir /var/www/<old folder> [options]
crosscode adopt <church> --undo
Moves an existing Cross Events install (hope-events at v2.1.x) to the monorepo, in
/var/www/sites/<church>/events. The old install keeps serving while the new one builds. The old
folder is kept as <old>.pre-2.2.0 for 14 days, for --undo.
--events-dir <dir> the existing install (required)
--version events@x.y.z the release to move to (default: the latest events@2.2.x)
--address <domain> the church's address, e.g. hopefamily.co.za (default: the Events
domain without "events.")
--undo go back to the old folder and the 2.1.x it ran
EOF
}
cmd_adopt() {
local church="" old="" version="" address="" undo=0
while [ $# -gt 0 ]; do
case "$1" in
--events-dir) [ $# -ge 2 ] || die "--events-dir needs a folder."; old="${2%/}"; shift 2 ;;
--version) [ $# -ge 2 ] || die "--version needs events@x.y.z."; version="$2"; shift 2 ;;
--address) [ $# -ge 2 ] || die "--address needs a domain."; address="$2"; shift 2 ;;
--undo) undo=1; shift ;;
-h|--help) adopt_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode adopt --help)." ;;
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
esac
done
[ -n "$church" ] || { adopt_usage; die "Name the church."; }
valid_slug "$church" || die "\"$church\" isn't a church name (a-z, 0-9 and -, starting with a letter)."
[ "$undo" = 1 ] || [ -n "$old" ] || { adopt_usage; die "--events-dir is required."; }
[ -z "$version" ] || [[ "$version" =~ ^events@[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || die "--version: expected events@x.y.z."
require_root
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/events.sh"
if [ "$undo" = 1 ]; then
adopt_undo "$church"
else
adopt_run "$church" "$old" "$version" "$address"
fi
}
# rewrite_ecosystem <old dir> <new app dir>, PM2 config on stdin → stdout: absolute paths into
# the old install (e.g. cwd: '/var/www/hope-events/backend') point into the new one instead.
# __dirname-based paths need nothing. Only whole paths match (/var/www/hope-events2 doesn't).
rewrite_ecosystem() {
local old new
old="$(printf '%s' "${1%/}" | sed 's/[][\.*^$#/]/\\&/g')"
new="$(printf '%s' "${2%/}" | sed 's/[\&#]/\\&/g')"
sed -E "s#([\"'\`])${old}(/|[\"'\`])#\\1${new}\\2#g"
}
# Ignored files in a checkout's folder (the install's own data, not in git), one per line.
ignored_files_in() { git_in "$1" ls-files --others --ignored --exclude-standard -- "$2"; }
adopt_run() {
local church="$1" old="$2" version="$3" address="$4"
local sites new app user oldref changes backend frontend api web dburl db domain major
sites="$(church_dir "$church")"
new="$sites/events"
app="$new/apps/events"
# ── 1. Checks ──────────────────────────────────────────────────────────────────────────────
step "Checks"
[ -d "$old/.git" ] && [ -d "$old/backend" ] || die "$old isn't a Cross Events install (no .git or backend/)."
oldref="$(git_in "$old" describe --tags --exact-match 2>/dev/null || true)"
[[ "$oldref" =~ ^v2\.1\.[0-9]+$ ]] ||
die "$old is on ${oldref:-an untagged commit}, not a v2.1.x release. Update it with its scripts/deploy.sh to v2.1.1 first."
changes="$(local_changes "$old" | awk 'substr($0, 4) != "ecosystem.config.js"')"
if [ -n "$changes" ]; then
warn "Files in $old were changed or added by hand:"
printf '%s\n' "$changes" | sed 's/^/ /' >&2
die "Sort them out first (as scripts/deploy.sh --check explains). Nothing was changed."
fi
if [ -f "$(church_env_path "$church")" ]; then
church_env_read "$(church_env_path "$church")"
[ -n "$(pvar events ADOPTED_AT)" ] && { info "$church is already adopted ($(pvar events DIR)). Nothing to do."; return 0; }
die "$(church_env_path "$church") already exists: $church is already set up on this server."
fi
[ ! -e "$new" ] || die "$new exists from an adopt that didn't finish. The old install is still the one running: remove $new and run adopt again."
[ ! -e "$old$ADOPT_SUFFIX" ] || die "$old$ADOPT_SUFFIX already exists. Move it away first."
if grep -rlsF -- "$old" /etc/nginx/ >/dev/null 2>&1; then
warn "nginx refers to $old directly:"
grep -rlsF -- "$old" /etc/nginx/ | sed 's/^/ /' >&2
die "Change those to proxy to the app (or to the new folder, $app) first: the old folder gets renamed."
fi
[ -f "$old/ecosystem.config.js" ] || die "$old has no ecosystem.config.js, so its PM2 names aren't known."
major="$(node_major)"
[ "$major" -ge "$CROSSCODE_NODE_MIN" ] || die "This server runs Node $(node -v 2>/dev/null || echo '(none)'); 2.2.0 needs $CROSSCODE_NODE_MIN or later."
# ── 2. What the install already has ───────────────────────────────────────────────────────
user="$(stat -c %U "$old")"
id "$user" >/dev/null 2>&1 && [ "$user" != root ] || die "$old is owned by $user; expected the app user."
# shellcheck disable=SC2016
read -r backend frontend web < <(run_as "$user" "$old" node -e '
const apps = require(process.argv[1]).apps || [];
const b = apps.find(a => /backend/.test(a.name)) || apps[0] || {};
const f = apps.find(a => /frontend/.test(a.name)) || apps[1] || {};
const m = /-p\s+(\d+)/.exec([].concat(f.args || []).join(" "));
console.log(b.name || "", f.name || "", m ? m[1] : "3000");' "$old/ecosystem.config.js") ||
die "Couldn't read the PM2 names from $old/ecosystem.config.js."
[ -n "$backend" ] && [ -n "$frontend" ] || die "Couldn't find the backend and frontend apps in $old/ecosystem.config.js."
api="$(env_value "$old/backend/.env" PORT)"
api="${api:-5000}"
dburl="$(env_value "$old/backend/.env" DATABASE_URL)"
db="$(db_name_from_url "$dburl")"
[ -n "$db" ] || die "No DATABASE_URL in $old/backend/.env."
domain="$(host_from_url "$(env_value "$old/backend/.env" FRONTEND_URL)")"
if [ -z "$address" ]; then
[[ "$domain" == events.* ]] || die "The Events domain is \"$domain\"; give the church's address with --address."
address="${domain#events.}"
fi
info "App user $user, PM2 $backend + $frontend, ports api $api web $web, database $db, domain $domain"
# church.env is written at the end; until then the values live in CENV only.
CENV=()
church_env_set CHURCH "$church"
church_env_set PRODUCTS events
church_env_set ADDRESS "$address"
church_env_set EVENTS_DIR "$new"
church_env_set EVENTS_DOMAIN "$domain"
church_env_set EVENTS_PM2 "$backend $frontend"
church_env_set EVENTS_PORTS "$api $web"
church_env_set EVENTS_DB "$db"
church_env_set EVENTS_USER "$user"
# ── 3. The new checkout ────────────────────────────────────────────────────────────────────
step "New checkout in $new"
mkdir -p "$sites"
chmod 755 "$CROSSCODE_SITES" "$sites"
mkdir "$new"
chown "$user:$user" "$new"
run_as "$user" "$new" git clone --quiet "$CROSSCODE_REPO" .
if [ -z "$version" ]; then
version="$(git_in "$new" tag -l 'events@2.2.*' | latest_tag_from events)"
[ -n "$version" ] || die "No events@2.2.x release tag yet. Remove $new; nothing else changed."
fi
git_in "$new" rev-parse -q --verify "refs/tags/$version" >/dev/null || die "There's no tag $version. Remove $new; nothing else changed."
run_as "$user" "$new" git checkout -q --detach "$version"
info "At $version"
# ── 4. The install's own files ────────────────────────────────────────────────────────────
step "Copying the install's own files"
local f
cp -p "$old/backend/.env" "$app/backend/.env"
for f in "$old"/frontend/.env*; do
[ -f "$f" ] && [ "$(basename "$f")" != .env.example ] && cp -p "$f" "$app/frontend/"
done
rewrite_ecosystem "$old" "$app" < "$old/ecosystem.config.js" > "$app/ecosystem.config.js"
chown "$user:$user" "$app/ecosystem.config.js"
adopt_sync_data "$old" "$app" ""
info "Uploads (this can take a while; the site is still running)"
mkdir -p "$app/backend/public/uploads"
rsync -a "$old/backend/public/uploads/" "$app/backend/public/uploads/"
[ -z "$(local_changes "$new")" ] || die "The copied files show up as changes in $new (git status). Remove $new; nothing else changed."
# ── 5. Build, next to the running install ─────────────────────────────────────────────────
step "Installing and building $version (the old install keeps serving)"
events_install_deps "$new" "$user"
events_build "$new" "$user"
local expected
expected="$(events_expected_version "$new")"
if events_pending_migrations "$new" "$user"; then
die "$version has database migrations that aren't applied (or the database can't be read). adopt only moves the install; run it at a 2.2.x without migrations. Remove $new; nothing else changed."
fi
# ── 6. Switch over: the only downtime ─────────────────────────────────────────────────────
step "Switching over"
info "Database backup"
events_backup "$new" "$user"
info "Last copy of uploads and data"
adopt_sync_data "$old" "$app" --delete
rsync -a --delete "$old/backend/public/uploads/" "$app/backend/public/uploads/"
set +e
(
set -e
run_as "$user" "$new" pm2 delete "$backend" "$frontend"
run_as "$user" "$app" pm2 start ecosystem.config.js
run_as "$user" "$app" pm2 save
wait_for_version "$(events_health_url)" "$expected" 60
)
local rc=$?
set -e
if [ "$rc" != 0 ]; then
warn "The new install didn't come up. Starting the old one again."
run_as "$user" "$old" pm2 delete "$backend" "$frontend" >/dev/null 2>&1 || true
run_as "$user" "$old" pm2 start ecosystem.config.js
run_as "$user" "$old" pm2 save
if wait_for_version "$(events_health_url)" "${oldref#v}" 60; then
die "Back on $oldref from $old, as before. $new is left for a look (pm2 logs); remove it before trying again."
fi
die "The old install didn't come back either: check now (pm2 status, pm2 logs)."
fi
# ── 7. Keep the old folder for --undo, and record the church ──────────────────────────────
mv "$old" "$old$ADOPT_SUFFIX"
church_env_set EVENTS_OLD_DIR "$old$ADOPT_SUFFIX"
church_env_set EVENTS_OLD_REF "$oldref"
church_env_set EVENTS_ADOPTED_AT "$(date +%F)"
church_env_write "$(church_env_path "$church")"
step "Adopted: $church runs $version from $new"
info "The old folder is $old$ADOPT_SUFFIX, kept $ADOPT_KEEP_DAYS days for \`crosscode adopt $church --undo\`."
info "Updates from now on: crosscode deploy $church events"
}
# adopt_sync_data <from install> <to app dir> [--delete]: the backend's data/*.json that aren't
# in git, and its backups.
adopt_sync_data() {
local from="$1" to="$2" del="$3" f
while IFS= read -r f; do
[ -n "$f" ] || continue
mkdir -p "$(dirname "$to/$f")"
cp -p "$from/$f" "$to/$f"
done < <(ignored_files_in "$from" backend/data)
if [ -d "$from/backend/backups" ]; then
mkdir -p "$to/backend/backups"
# shellcheck disable=SC2086
rsync -a $del "$from/backend/backups/" "$to/backend/backups/"
fi
}
# adopt --undo: back to the old folder and the 2.1.x it ran, while it's kept.
adopt_undo() {
local church="$1" new app user oldkept orig oldref backend frontend extra
load_church "$church"
new="$(pvar events DIR)"
app="$new/apps/events"
user="$(pvar events USER)"
oldkept="$(pvar events OLD_DIR)"
oldref="$(pvar events OLD_REF)"
read -r backend frontend <<< "$(pvar events PM2)"
[ -n "$oldkept" ] || die "$church wasn't moved with adopt, so there's nothing to go back to."
[ -d "$oldkept" ] || die "The old folder $oldkept is gone, so adopt --undo can't go back any more."
orig="${oldkept%"$ADOPT_SUFFIX"}"
[ ! -e "$orig" ] || die "$orig exists again; move it away first."
step "Checks"
# The database must still suit 2.1.x: no migrations the old release doesn't have.
extra="$(comm -13 \
<(find "$oldkept/backend/prisma/migrations" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort) \
<(find "$app/backend/prisma/migrations" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort))"
[ -z "$extra" ] || die "$(checkout_ref "$new" events) has database migrations $oldref doesn't know ($(echo "$extra" | tr '\n' ' ')). Going back would break it; restore a backup instead."
step "Database backup"
events_backup "$new" "$user"
step "Going back to $oldref in $orig"
mv "$oldkept" "$orig"
info "Copying back uploads and data added since"
adopt_sync_data "$app" "$orig" ""
rsync -a "$app/backend/public/uploads/" "$orig/backend/public/uploads/"
set +e
(
set -e
run_as "$user" "$orig" pm2 delete "$backend" "$frontend"
run_as "$user" "$orig" pm2 start ecosystem.config.js
run_as "$user" "$orig" pm2 save
wait_for_version "$(events_health_url)" "${oldref#v}" 60
)
local rc=$?
set -e
if [ "$rc" != 0 ]; then
warn "$oldref didn't come up. Starting $(checkout_ref "$new" events) from $new again."
run_as "$user" "$app" pm2 delete "$backend" "$frontend" >/dev/null 2>&1 || true
mv "$orig" "$oldkept"
run_as "$user" "$app" pm2 start ecosystem.config.js
run_as "$user" "$app" pm2 save
die "Undo failed; $church runs from $new as before."
fi
# The church's folder goes aside (not deleted), so it's no longer a church here and adopt can
# be run again.
local aside
aside="$CROSSCODE_SITES/.undone-$church-$(date +%Y%m%d%H%M%S)"
mv "$(church_dir "$church")" "$aside"
step "Undone: $church runs $oldref from $orig again"
info "The monorepo checkout is in $aside; remove it when you no longer need it."
}
+328
View File
@@ -0,0 +1,328 @@
# shellcheck shell=bash
# Shared helpers for the crosscode script: logging, users, church.env, tags, versions, health.
# Only functions and defaults: sourcing this file changes nothing (the bats tests rely on that).
CROSSCODE_SITES="${CROSSCODE_SITES:-/var/www/sites}"
CROSSCODE_REPO="${CROSSCODE_REPO:-https://c-git.crosscode.co.za/joshua/crosscode-platform.git}"
# Every deploy runs the products in this order (ROADMAP §8): Accounts first, since others sign in
# through it.
PRODUCT_ORDER=(accounts events website app)
# Products this version of the script can deploy (a products/<name>.sh exists for each).
SUPPORTED_PRODUCTS=(events)
# Releases older than this get a warning; older than CROSSCODE_NODE_MIN the deploy is refused.
CROSSCODE_NODE_MIN=20
CROSSCODE_NODE_WARN=22
# ── Logging ──────────────────────────────────────────────────────────────────────────────────
step() { printf '==> %s\n' "$*"; }
info() { printf ' %s\n' "$*"; }
warn() { printf '!!> %s\n' "$*" >&2; }
die() { printf '!!> %s\n' "$*" >&2; exit 1; }
# ── Small checks ─────────────────────────────────────────────────────────────────────────────
require_root() {
# The bats tests run deploys against stub products as an ordinary user.
[ "${CROSSCODE_TEST:-}" = 1 ] && return 0
[ "$(id -u)" = 0 ] || die "Run this as root (sudo crosscode …): it reads church.env (root only) and runs each app as its own user."
}
# A church's short name: lower case letters, digits and -, starting with a letter.
valid_slug() { [[ "$1" =~ ^[a-z][a-z0-9-]{0,39}$ ]]; }
is_known_product() {
local p
for p in "${PRODUCT_ORDER[@]}"; do [ "$p" = "$1" ] && return 0; done
return 1
}
is_supported_product() {
local p
for p in "${SUPPORTED_PRODUCTS[@]}"; do [ "$p" = "$1" ] && return 0; done
return 1
}
# A product's place in the deploy order (0 for accounts).
product_index() {
local i
for i in "${!PRODUCT_ORDER[@]}"; do [ "${PRODUCT_ORDER[$i]}" = "$1" ] && { echo "$i"; return 0; }; done
echo 99
}
# The products given (any order, repeats allowed), printed in deploy order, one per line.
in_product_order() {
local p q
for p in "${PRODUCT_ORDER[@]}"; do
for q in "$@"; do
if [ "$p" = "$q" ]; then echo "$p"; break; fi
done
done
}
# Upper case for church.env keys: events → EVENTS.
upper() { printf '%s' "$1" | tr '[:lower:]-' '[:upper:]_'; }
# ── Running things as the app user ───────────────────────────────────────────────────────────
# run_as <user> <dir> <command…>: runs the command in <dir> as <user> (directly when we already
# are that user), with that user's HOME so PM2 and npm use their own folders.
run_as() {
local user="$1" dir="$2"
shift 2
if [ "$(id -un)" = "$user" ]; then
(cd -- "$dir" && "$@")
else
sudo -u "$user" -H -- bash -c 'cd -- "$1" && shift && exec "$@"' crosscode-run "$dir" "$@"
fi
}
# ── church.env ───────────────────────────────────────────────────────────────────────────────
# /var/www/sites/<church>/church.env holds names, folders, domains and ports (never secrets). It is
# read as data, never sourced: only KEY=VALUE lines with known keys are taken, into CENV.
declare -gA CENV=()
church_dir() { printf '%s/%s' "$CROSSCODE_SITES" "$1"; }
church_env_path() { printf '%s/%s/church.env' "$CROSSCODE_SITES" "$1"; }
church_env_key_ok() {
[[ "$1" =~ ^(CHURCH|PRODUCTS|ADDRESS)$ ]] || [[ "$1" =~ ^(ACCOUNTS|EVENTS|WEBSITE|APP)_[A-Z0-9_]+$ ]]
}
# church_env_read <file>: fills CENV. Values may be bare or in double or single quotes; a
# "# comment" after the value is ignored. Unknown keys and other lines are skipped.
church_env_read() {
local file="$1" line key value
CENV=()
[ -f "$file" ] || return 1
while IFS= read -r line || [ -n "$line" ]; do
line="${line%$'\r'}"
[[ "$line" =~ ^[[:space:]]*([A-Z][A-Z0-9_]*)=(.*)$ ]] || continue
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
church_env_key_ok "$key" || continue
if [[ "$value" =~ ^\"([^\"]*)\" ]] || [[ "$value" =~ ^\'([^\']*)\' ]]; then
value="${BASH_REMATCH[1]}"
else
value="${value%%#*}"
value="${value%"${value##*[![:space:]]}"}"
fi
CENV[$key]="$value"
done < "$file"
}
# cenv <KEY> [default]: a value from CENV.
cenv() { printf '%s' "${CENV[$1]:-${2:-}}"; }
# pvar <product> <NAME> [default]: a product's value, e.g. pvar events DIR → CENV[EVENTS_DIR].
pvar() { cenv "$(upper "$1")_$2" "${3:-}"; }
church_env_set() {
church_env_key_ok "$1" || die "church.env: unknown key $1"
[[ "$2" != *[\"\'\$\`\\]* && "$2" != *$'\n'* ]] || die "church.env: $1 can't contain quotes, \$, \` , \\ or newlines"
CENV[$1]="$2"
}
church_env_unset() { unset 'CENV[$1]'; }
# church_env_write <file>: writes CENV in a fixed order (CHURCH, PRODUCTS, ADDRESS, then each
# product's keys in deploy order), atomically, mode 600.
church_env_write() {
local file="$1" tmp key p prefix
local -a keys=()
for key in CHURCH PRODUCTS ADDRESS; do [ -n "${CENV[$key]+x}" ] && keys+=("$key"); done
for p in "${PRODUCT_ORDER[@]}"; do
prefix="$(upper "$p")_"
while IFS= read -r key; do [ -n "$key" ] && keys+=("$key"); done < <(
for key in "${!CENV[@]}"; do [[ "$key" == "$prefix"* ]] && echo "$key"; done | LC_ALL=C sort
)
done
tmp="$(mktemp "$(dirname "$file")/.church.env.XXXXXX")"
{
echo "# Written by crosscode. Names, folders, domains and ports only: secrets stay in each product's .env."
for key in "${keys[@]}"; do
if [[ "${CENV[$key]}" =~ [[:space:]#] || -z "${CENV[$key]}" ]]; then
printf '%s="%s"\n' "$key" "${CENV[$key]}"
else
printf '%s=%s\n' "$key" "${CENV[$key]}"
fi
done
} > "$tmp"
chmod 600 "$tmp"
mv -f "$tmp" "$file"
}
# Church names on this server: every folder in $CROSSCODE_SITES with a church.env.
list_churches() {
local f
for f in "$CROSSCODE_SITES"/*/church.env; do
[ -f "$f" ] && basename "$(dirname "$f")"
done
return 0
}
# Loads a church's church.env into CENV, or stops.
load_church() {
valid_slug "$1" || die "\"$1\" isn't a church name (a-z, 0-9 and -)."
church_env_read "$(church_env_path "$1")" || die "No church \"$1\" on this server ($(church_env_path "$1") is missing)."
}
church_has_product() {
local p
for p in $(cenv PRODUCTS); do [ "$p" = "$1" ] && return 0; done
return 1
}
# ── Versions and tags ────────────────────────────────────────────────────────────────────────
# version_ge <a> <b>: a >= b, for x.y.z with an optional -prerelease (1.2.0-rc1 < 1.2.0).
version_ge() {
local a="$1" b="$2" an bn ap bp i x y
an="${a%%-*}"; bn="${b%%-*}"
ap=""; bp=""
[[ "$a" == *-* ]] && ap="${a#*-}"
[[ "$b" == *-* ]] && bp="${b#*-}"
local -a A B
IFS=. read -r -a A <<< "$an"
IFS=. read -r -a B <<< "$bn"
for i in 0 1 2; do
x="${A[$i]:-0}"; y="${B[$i]:-0}"
[[ "$x" =~ ^[0-9]+$ && "$y" =~ ^[0-9]+$ ]] || return 2
if ((10#$x > 10#$y)); then return 0; fi
if ((10#$x < 10#$y)); then return 1; fi
done
# Same x.y.z: a release beats its prereleases; prereleases compare as text.
if [ -z "$ap" ]; then return 0; fi
if [ -z "$bp" ]; then return 1; fi
[[ "$ap" > "$bp" || "$ap" == "$bp" ]]
}
# tag_version <product@x.y.z> → x.y.z
tag_version() { printf '%s' "${1#*@}"; }
# latest_tag <product>, reading tag names on stdin: the newest released product@x.y.z
# (prerelease and test tags such as events@2.2.0-test are never "latest").
latest_tag_from() {
local p="$1" t best=""
while IFS= read -r t; do
[[ "$t" =~ ^${p}@[0-9]+\.[0-9]+\.[0-9]+$ ]] || continue
if [ -z "$best" ] || version_ge "$(tag_version "$t")" "$(tag_version "$best")"; then best="$t"; fi
done
printf '%s' "$best"
}
# git_in <checkout> <args…>: git for reading a checkout owned by the app user (as root, git would
# otherwise refuse it as "dubious ownership"). Anything that writes runs as the app user instead.
git_in() {
local dir="$1"
shift
git -c safe.directory="$dir" -C "$dir" "$@"
}
# latest_tag <checkout> <product>: from the checkout's tags (fetch first).
latest_tag() { git_in "$1" tag -l "$2@*" | latest_tag_from "$2"; }
# checkout_ref <checkout> <product>: the product tag the checkout is on, or the short commit.
checkout_ref() {
git_in "$1" describe --tags --exact-match --match "$2@*" 2>/dev/null || git_in "$1" rev-parse --short HEAD
}
# whatsnew_requires <version>, reading a WHATS-NEW.md on stdin: the requirements in that
# version's heading, one "product x.y.z" per line. Same grammar as the Hub's release sync
# (events-hub releaseSync.js): "## 3.0.0 — requires accounts 1.2.0, website 1.1.0 — urgent".
# HTML comments are skipped (the file's own instructions contain example headings).
whatsnew_requires() {
local version="$1"
awk -v want="$version" '
BEGIN { products = "accounts|events|website|app" }
{
line = $0
sub(/\r$/, "", line)
# Drop <!-- … --> comments, which can span lines.
out = ""
while (line != "") {
if (incomment) {
e = index(line, "-->")
if (e == 0) { line = ""; break }
line = substr(line, e + 3); incomment = 0
} else {
s = index(line, "<!--")
if (s == 0) { out = out line; line = ""; break }
out = out substr(line, 1, s - 1); line = substr(line, s + 4); incomment = 1
}
}
if (out !~ /^##[ \t]+/) next
h = out; sub(/^##[ \t]+/, "", h)
if (!match(h, /v?[0-9]+\.[0-9]+\.[0-9]+/)) next
v = substr(h, RSTART, RLENGTH); sub(/^v/, "", v)
if (v != want) next
rest = tolower(substr(h, RSTART + RLENGTH))
if (!match(rest, /(^|[^a-z])requires?([^a-z]|$)/)) exit
rest = substr(rest, RSTART)
while (match(rest, "(" products ")[ \t]+v?[0-9]+\\.[0-9]+\\.[0-9]+")) {
m = substr(rest, RSTART, RLENGTH)
before = RSTART > 1 ? substr(rest, RSTART - 1, 1) : " "
rest = substr(rest, RSTART + RLENGTH)
if (before ~ /[a-z0-9]/) continue
split(m, parts, /[ \t]+/)
p = parts[1]; ver = parts[2]; sub(/^v/, "", ver)
if (!(p in seen)) { seen[p] = 1; print p " " ver }
}
exit
}
'
}
# ── .env files and URLs ──────────────────────────────────────────────────────────────────────
# env_value <file> <KEY>: a value from a .env file (quotes removed), "" when absent.
env_value() {
local line
line="$(grep -E "^[[:space:]]*(export[[:space:]]+)?$2=" "$1" 2>/dev/null | tail -n 1)" || true
line="${line#*=}"
line="${line%$'\r'}"
if [[ "$line" =~ ^\"(.*)\"$ ]] || [[ "$line" =~ ^\'(.*)\'$ ]]; then line="${BASH_REMATCH[1]}"; fi
printf '%s' "$line"
}
# db_name_from_url <postgresql://user:pass@host:5432/name?x=y> → name
db_name_from_url() {
local u="${1%%\?*}"
printf '%s' "${u##*/}"
}
# host_from_url <https://events.church.org/x> → events.church.org (the first, if a list)
host_from_url() {
local u="${1%%,*}"
u="${u#*://}"
u="${u%%/*}"
printf '%s' "${u%%:*}"
}
# ── Health ───────────────────────────────────────────────────────────────────────────────────
# json_get <path>, reading JSON on stdin: a value ("a.b"), objects as compact JSON, "" if absent.
json_get() {
node -e '
let s = "";
process.stdin.on("data", d => (s += d)).on("end", () => {
try {
const v = process.argv[1].split(".").reduce((o, k) => (o == null ? o : o[k]), JSON.parse(s));
process.stdout.write(v == null ? "" : typeof v === "object" ? JSON.stringify(v) : String(v));
} catch { process.exit(1); }
});' "$1"
}
health_json() { curl -fsS --max-time 5 "$1" 2>/dev/null; }
# wait_for_version <health url> <version> [seconds]: until /health answers with that version.
wait_for_version() {
local url="$1" want="$2" limit="${3:-60}" waited=0 got=""
while [ "$waited" -lt "$limit" ]; do
got="$(health_json "$url" | json_get version 2>/dev/null || true)"
[ "$got" = "$want" ] && return 0
sleep 2
waited=$((waited + 2))
done
warn "/health ($url) didn't report $want within ${limit}s (last answer: ${got:-none})."
return 1
}
node_major() { node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0; }
# Files changed or added by hand in a checkout (ignored files such as .env, uploads, backups and
# the install's ecosystem.config.js never count).
local_changes() { git_in "$1" status --porcelain --untracked-files=all; }
+293
View File
@@ -0,0 +1,293 @@
# shellcheck shell=bash
# crosscode deploy: checks first for every product named, then each product in a fixed order
# (Accounts, Events, Website, App), each rolled back on its own if it fails (ROADMAP §8).
deploy_usage() {
cat <<'EOF'
crosscode deploy <church> [events] [website] [app] [options]
crosscode deploy --every-church [events] [website] [app] [options]
Updates Accounts (always, once the church has it) and the products named, to their latest
released tags. Products not named aren't touched.
--version <product>@<x.y.z> that release instead of the latest (repeatable, one per product)
--main the latest main instead of a tag (staging churches only)
--check only the checks; changes nothing
--allow-local-changes deploy even if files in a checkout were changed by hand
EOF
}
# Set by cmd_deploy, read by deploy_church.
declare -gA DEPLOY_VERSION=()
DEPLOY_MAIN=0
DEPLOY_CHECK=0
DEPLOY_EVERY=0
cmd_deploy() {
local church="" arg p
local -a named=()
while [ $# -gt 0 ]; do
arg="$1"
case "$arg" in
--version)
[ $# -ge 2 ] || die "--version needs <product>@<x.y.z>."
[[ "$2" =~ ^([a-z]+)@[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || die "--version $2: expected <product>@<x.y.z>, e.g. events@2.2.0."
p="${BASH_REMATCH[1]}"
is_known_product "$p" || die "--version $2: unknown product \"$p\"."
DEPLOY_VERSION[$p]="$2"
shift 2 ;;
--main) DEPLOY_MAIN=1; shift ;;
--check) DEPLOY_CHECK=1; shift ;;
--allow-local-changes) ALLOW_LOCAL_CHANGES=1; shift ;;
--every-church) DEPLOY_EVERY=1; shift ;;
-h|--help) deploy_usage; return 0 ;;
-*) die "Unknown option $arg (crosscode deploy --help)." ;;
*)
if [ "$DEPLOY_EVERY" = 0 ] && [ -z "$church" ]; then
church="$arg"
else
is_known_product "$arg" || die "Unknown product \"$arg\" (accounts, events, website, app)."
named+=("$arg")
fi
shift ;;
esac
done
[ "$DEPLOY_MAIN" = 0 ] || [ "${#DEPLOY_VERSION[@]}" = 0 ] || die "Use --main or --version, not both."
# The church name was taken as the first word; with --every-church after it, it's a product.
if [ "$DEPLOY_EVERY" = 1 ] && [ -n "$church" ]; then
is_known_product "$church" || die "--every-church doesn't take a church name."
named=("$church" "${named[@]}")
church=""
fi
for p in "${!DEPLOY_VERSION[@]}"; do
[ "$p" = accounts ] || printf '%s\n' "${named[@]}" | grep -qx "$p" ||
die "--version ${DEPLOY_VERSION[$p]}: name $p as well (crosscode deploy <church> $p --version …)."
done
require_root
if [ "$DEPLOY_EVERY" = 1 ]; then
local -a churches
mapfile -t churches < <(list_churches)
[ "${#churches[@]}" -gt 0 ] || die "No churches on this server ($CROSSCODE_SITES/*/church.env)."
local i rc
for i in "${!churches[@]}"; do
echo
step "Church ${churches[$i]} ($((i + 1)) of ${#churches[@]})"
set +e
(deploy_church "${churches[$i]}" "${named[@]}")
rc=$?
set -e
if [ "$rc" != 0 ]; then
warn "Stopped at ${churches[$i]}. Not reached: ${churches[*]:$((i + 1))}"
return 1
fi
done
return 0
fi
[ -n "$church" ] || { deploy_usage; die "Name a church, or use --every-church."; }
deploy_church "$church" "${named[@]}"
}
# deploy_church <church> [products…]: the checks, then the deploy. Must be called as a plain
# command (not in `if` or after `||`), so `set -e` keeps working inside it.
deploy_church() {
local church="$1"
shift
load_church "$church"
local p rp rv
local -a wanted=() products=()
church_has_product accounts && wanted+=(accounts)
for p in "$@"; do
if church_has_product "$p"; then
wanted+=("$p")
elif [ "$DEPLOY_EVERY" = 1 ]; then
info "$church has no $p: skipped."
else
die "$church has no $p (its products: $(cenv PRODUCTS))."
fi
done
mapfile -t products < <(in_product_order "${wanted[@]}")
if [ "${#products[@]}" = 0 ]; then
info "Nothing to deploy for $church. Name the products to update (its products: $(cenv PRODUCTS))."
return 0
fi
# ── 1. Checks, for every product, before anything is touched ──────────────────────────────
step "Checks for $church: ${products[*]}"
local -A DIR=() USR=() PREV=() TARGET=() TVER=()
local failed=0 dir user changes major t v
major="$(node_major)"
if [ "$major" -lt "$CROSSCODE_NODE_MIN" ]; then
warn "This server runs Node $(node -v 2>/dev/null || echo '(none)'). Releases need Node $CROSSCODE_NODE_MIN or later (24 LTS recommended)."
failed=1
elif [ "$major" -lt "$CROSSCODE_NODE_WARN" ]; then
warn "This server runs Node $(node -v), which no longer gets security fixes. Move to Node 24 LTS."
fi
for p in "${products[@]}"; do
is_supported_product "$p" || die "This version of crosscode can't deploy $p yet."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$p.sh"
dir="$(pvar "$p" DIR)"
user="$(pvar "$p" USER)"
if [ -z "$dir" ] || [ ! -d "$dir/.git" ]; then warn "$p: $dir isn't a checkout (church.env $(upper "$p")_DIR)."; failed=1; continue; fi
if [ -z "$user" ] || ! id "$user" >/dev/null 2>&1; then warn "$p: no app user \"$user\" (church.env $(upper "$p")_USER)."; failed=1; continue; fi
DIR[$p]="$dir"; USR[$p]="$user"
if ! run_as "$user" "$dir" git fetch --tags --quiet origin; then
warn "$p: couldn't fetch from origin."; failed=1; continue
fi
PREV[$p]="$(checkout_ref "$dir" "$p")"
if [ -n "${DEPLOY_VERSION[$p]:-}" ]; then
t="${DEPLOY_VERSION[$p]}"
git_in "$dir" rev-parse -q --verify "refs/tags/$t" >/dev/null || { warn "$p: there's no tag $t."; failed=1; continue; }
elif [ "$DEPLOY_MAIN" = 1 ]; then
t="origin/main"
else
t="$(latest_tag "$dir" "$p")"
[ -n "$t" ] || { warn "$p: no $p@x.y.z release tags found."; failed=1; continue; }
fi
TARGET[$p]="$t"
if [ "$t" = origin/main ]; then TVER[$p]=""; else TVER[$p]="$(tag_version "$t")"; fi
changes="$(local_changes "$dir")"
if [ -n "$changes" ]; then
warn "$p: files in $dir were changed or added by hand:"
printf '%s\n' "$changes" | sed 's/^/ /' >&2
info "A release would build them in (or refuse to replace them). Move added files (??) out of"
info "the folder and put changed ones ( M) back with \"git checkout -- <file>\", after checking"
info "nothing in them is needed."
if [ "${ALLOW_LOCAL_CHANGES:-}" = 1 ] && [ "$DEPLOY_CHECK" = 0 ]; then
info "--allow-local-changes: deploying anyway."
else
failed=1
fi
fi
done
[ "$failed" = 0 ] || die "Checks failed for $church. Nothing was changed."
# Requirements between products (decision 24): from the target release's WHATS-NEW.md heading.
local req_ok
for p in "${products[@]}"; do
[ -n "${TVER[$p]}" ] || { info "$p: deploying main, so no release requirements to check."; continue; }
while read -r rp rv; do
[ -n "$rp" ] && [ "$rp" != "$p" ] || continue
req_ok=0
if [ -n "${TARGET[$rp]:-}" ] && [ "$(product_index "$rp")" -lt "$(product_index "$p")" ]; then
# Updated earlier in this same run.
if [ -z "${TVER[$rp]}" ] || version_ge "${TVER[$rp]}" "$rv"; then req_ok=1; fi
v="${TVER[$rp]:-main}"
elif church_has_product "$rp"; then
v="$(checkout_ref "$(pvar "$rp" DIR)" "$rp" 2>/dev/null || true)"
v="$(tag_version "$v")"
version_ge "$v" "$rv" 2>/dev/null && req_ok=1
else
v="not installed"
fi
if [ "$req_ok" = 1 ]; then
info "$p ${TVER[$p]} requires $rp $rv: met ($rp ${v})."
else
warn "$p ${TVER[$p]} requires $rp $rv, and $church has $rp ${v:-unknown}. Update $rp first (or in the same run)."
failed=1
fi
done < <(git_in "${DIR[$p]}" show "${TARGET[$p]}:apps/$p/WHATS-NEW.md" 2>/dev/null | whatsnew_requires "${TVER[$p]}")
done
[ "$failed" = 0 ] || die "Requirements not met for $church. Nothing was changed."
for p in "${products[@]}"; do
if [ "${PREV[$p]}" = "${TARGET[$p]}" ]; then
info "$p: already on ${PREV[$p]}."
else
info "$p: ${PREV[$p]} → ${TARGET[$p]}"
fi
done
if [ "$DEPLOY_CHECK" = 1 ]; then
step "Checks passed for $church: ready to deploy."
return 0
fi
# ── 2. Each product in order; a failure rolls that product back and stops the run ─────────
local -A RESULT=()
local stopped=0
for p in "${products[@]}"; do
if [ "$stopped" = 1 ]; then RESULT[$p]="not reached"; continue; fi
if [ "${PREV[$p]}" = "${TARGET[$p]}" ]; then RESULT[$p]="already on ${PREV[$p]}"; continue; fi
deploy_product "$p" "${DIR[$p]}" "${USR[$p]}" "${PREV[$p]}" "${TARGET[$p]}"
RESULT[$p]="$DEPLOY_RESULT"
[ "$DEPLOY_OK" = 1 ] || stopped=1
done
echo
step "Summary for $church"
for p in "${products[@]}"; do info "$(printf '%-9s %s' "$p" "${RESULT[$p]}")"; done
[ "$stopped" = 0 ] || return 1
}
# deploy_product <product> <checkout> <user> <previous ref> <target ref>: sets DEPLOY_OK and
# DEPLOY_RESULT. Always returns 0, so `set -e` inside the steps works (see deploy_church).
deploy_product() {
local p="$1" dir="$2" user="$3" prev="$4" target="$5" stage_file rc stage
stage_file="$(mktemp)"
echo
step "$p: $prev → $target"
set +e
(
set -e
echo backup > "$stage_file"
step "$p: backing up the database"
"${p}_backup" "$dir" "$user"
echo checkout > "$stage_file"
step "$p: checking out $target"
run_as "$user" "$dir" git checkout -q --detach "$target"
step "$p: installing"
"${p}_install_deps" "$dir" "$user"
step "$p: migrations"
"${p}_migrate" "$dir" "$user"
step "$p: building"
"${p}_build" "$dir" "$user"
expected="$("${p}_expected_version" "$dir")"
echo reload > "$stage_file"
step "$p: reloading PM2"
"${p}_reload" "$dir" "$user"
step "$p: waiting for /health to report $expected"
wait_for_version "$("${p}_health_url")" "$expected" 60
)
rc=$?
set -e
stage="$(cat "$stage_file")"
rm -f "$stage_file"
if [ "$rc" = 0 ]; then
DEPLOY_OK=1
DEPLOY_RESULT="updated $prev → $(checkout_ref "$dir" "$p")"
return 0
fi
DEPLOY_OK=0
if [ "$stage" = backup ]; then
warn "$p: the backup failed, so nothing was changed."
DEPLOY_RESULT="failed at the backup; still on $prev, nothing changed"
return 0
fi
warn "$p: deploy failed. Going back to $prev (database migrations aren't undone; the backup has the database as it was)."
set +e
(
set -e
run_as "$user" "$dir" git checkout -q --detach "$prev"
"${p}_rollback_build" "$dir" "$user"
if [ "$stage" = reload ]; then
"${p}_reload" "$dir" "$user"
wait_for_version "$("${p}_health_url")" "$("${p}_expected_version" "$dir")" 60
fi
)
rc=$?
set -e
if [ "$rc" = 0 ]; then
if [ "$stage" = reload ]; then
DEPLOY_RESULT="FAILED, rolled back to $prev and running again"
else
DEPLOY_RESULT="FAILED, rolled back to $prev (the running version was never stopped)"
fi
else
DEPLOY_RESULT="FAILED, and going back to $prev failed too: check it now (crosscode status, pm2 logs)"
fi
return 0
}
+254
View File
@@ -0,0 +1,254 @@
# shellcheck shell=bash
# crosscode install: a new church on this server (from hope-events' scripts/install.sh 2.1.x).
# Events only in 2.2.0; Accounts, Website and App follow as their products/*.sh are added.
install_usage() {
cat <<'EOF'
crosscode install <church> --products events --domain <address> [options]
A new church: system packages (Node 24, PostgreSQL, PM2, nginx, certbot) if missing, then per
product an app user, database, checkout, .env, PM2 processes, nginx site and certificate.
Writes /var/www/sites/<church>/church.env. DNS must already point here (it prints the records).
--products events the products to install (only events in this version)
--domain <address> the church's address: hopefamily.co.za or hopefamily.crosscode.co.za;
Events is served on events.<address>
--events-domain <domain> serve Events somewhere else instead
--email <email> for Let's Encrypt notices (required unless --no-ssl)
--version events@x.y.z that release (default: the latest)
--main the latest main (staging churches only)
--user <name> the Linux user the apps run as (default: cc-<church>)
--api-port <n> Events backend port (default: the first free one from 5000)
--web-port <n> Events frontend port (default: the first free one from 3000)
--no-ssl no certificate (behind another proxy that does HTTPS)
EOF
}
# Ports in use: every church's *_PORTS on this server, and anything listening now.
used_ports() {
local f
for f in "$CROSSCODE_SITES"/*/church.env; do
[ -f "$f" ] && sed -nE 's/^[A-Z]+_PORTS="?([0-9 ]+)"?.*/\1/p' "$f" | tr ' ' '\n'
done
ss -ltnH 2>/dev/null | awk '{ n = split($4, a, ":"); print a[n] }'
return 0
}
# free_port <from> <taken…>: the first port from <from> not in the list.
free_port() {
local p="$1"
shift
while printf '%s\n' "$@" | grep -qx "$p"; do p=$((p + 1)); done
echo "$p"
}
random_secret() { openssl rand -base64 64 | tr -d '/+=\n' | head -c "${1:-48}"; }
cmd_install() {
local church="" products="" address="" events_domain="" email="" version="" main=0 user="" api="" web="" ssl=1
while [ $# -gt 0 ]; do
case "$1" in
--products) products="$(printf '%s' "$2" | tr ',' ' ')"; shift 2 ;;
--domain) address="$2"; shift 2 ;;
--events-domain) events_domain="$2"; shift 2 ;;
--email) email="$2"; shift 2 ;;
--version) version="$2"; shift 2 ;;
--main) main=1; shift ;;
--user) user="$2"; shift 2 ;;
--api-port) api="$2"; shift 2 ;;
--web-port) web="$2"; shift 2 ;;
--no-ssl) ssl=0; shift ;;
-h|--help) install_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode install --help)." ;;
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
esac
done
[ -n "$church" ] || { install_usage; die "Name the church."; }
valid_slug "$church" || die "\"$church\" isn't a church name (a-z, 0-9 and -, starting with a letter)."
[ -n "$products" ] || die "--products is required (e.g. --products events)."
local p
for p in $products; do
is_known_product "$p" || die "Unknown product \"$p\"."
[ "$p" = events ] || die "This version of crosscode can only install events."
done
[[ "$address" =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$ ]] || die "--domain: give the church's address, e.g. hopefamily.co.za."
events_domain="${events_domain:-events.$address}"
[ "$ssl" = 0 ] || [ -n "$email" ] || die "--email is required for the certificate (or use --no-ssl)."
[ -z "$version" ] || [[ "$version" =~ ^events@[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || die "--version: expected events@x.y.z."
[ "$main" = 0 ] || [ -z "$version" ] || die "Use --main or --version, not both."
user="${user:-cc-$church}"
user="${user:0:32}"
require_root
[ ! -f "$(church_env_path "$church")" ] || die "$church is already installed here (crosscode status $church). New products for it come with \`crosscode add\` (phase 3)."
local taken
mapfile -t taken < <(used_ports)
api="${api:-$(free_port 5000 "${taken[@]}")}"
web="${web:-$(free_port 3000 "${taken[@]}" "$api")}"
[[ "$api" =~ ^[0-9]+$ && "$web" =~ ^[0-9]+$ && "$api" != "$web" ]] || die "Ports must be two different numbers."
install_system_packages "$ssl"
step "App user ($user)"
id "$user" >/dev/null 2>&1 || useradd --create-home --shell /bin/bash "$user"
CENV=()
church_env_set CHURCH "$church"
church_env_set PRODUCTS "events"
church_env_set ADDRESS "$address"
install_events "$church" "$user" "$events_domain" "$api" "$web" "$version" "$main" "$ssl" "$email"
church_env_write "$(church_env_path "$church")"
step "Done"
info "DNS (if not set yet): $events_domain → this server (A record, or a CNAME)."
info "Open https://$events_domain/setup to create the admin account, then enter the licence key."
info "Updates: crosscode deploy $church events"
}
install_system_packages() {
local ssl="$1"
step "System packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -q
apt-get install -y -q curl git rsync nginx postgresql postgresql-client openssl build-essential ca-certificates gnupg
[ "$ssl" = 0 ] || apt-get install -y -q certbot python3-certbot-nginx
# Node 24 is the LTS line supported until April 2028.
if ! command -v node >/dev/null || [ "$(node_major)" -lt 24 ]; then
step "Node.js 24"
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
apt-get install -y -q nodejs
fi
command -v pm2 >/dev/null || npm install -g pm2
}
install_events() {
local church="$1" user="$2" domain="$3" api="$4" web="$5" version="$6" main="$7" ssl="$8" email="$9"
local dir app db pass url name scheme
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/events.sh"
dir="$(church_dir "$church")/events"
app="$dir/apps/events"
db="$(printf '%s_events' "$church" | tr '-' '_')"
name="$church-events"
scheme=https
[ "$ssl" = 1 ] || scheme=http
url="$scheme://$domain"
church_env_set EVENTS_DIR "$dir"
church_env_set EVENTS_DOMAIN "$domain"
church_env_set EVENTS_PM2 "$name-backend $name-frontend"
church_env_set EVENTS_PORTS "$api $web"
church_env_set EVENTS_DB "$db"
church_env_set EVENTS_USER "$user"
step "Events: code ($dir)"
mkdir -p "$(church_dir "$church")"
chmod 755 "$CROSSCODE_SITES" "$(church_dir "$church")"
if [ ! -d "$dir/.git" ]; then
mkdir -p "$dir"
chown "$user:$user" "$dir"
run_as "$user" "$dir" git clone --quiet "$CROSSCODE_REPO" .
fi
run_as "$user" "$dir" git fetch --tags --quiet origin
if [ "$main" = 1 ]; then
version=origin/main
elif [ -z "$version" ]; then
version="$(latest_tag "$dir" events)"
[ -n "$version" ] || die "No events@x.y.z release tags yet (use --version or --main)."
fi
run_as "$user" "$dir" git checkout -q --detach "$version"
info "At $(checkout_ref "$dir" events)"
step "Events: database ($db)"
# Re-running keeps the password already in backend/.env; otherwise a new one.
pass=""
if [ -f "$app/backend/.env" ]; then
pass="$(env_value "$app/backend/.env" DATABASE_URL | sed -nE 's#^postgresql://[^:]+:([^@]+)@.*#\1#p')"
fi
pass="${pass:-$(random_secret 32)}"
sudo -u postgres psql -v ON_ERROR_STOP=1 -q <<SQL
DO \$\$ BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '$db') THEN
CREATE ROLE "$db" LOGIN PASSWORD '$pass';
ELSE
ALTER ROLE "$db" WITH LOGIN PASSWORD '$pass';
END IF;
END \$\$;
SQL
sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname = '$db'" | grep -q 1 ||
sudo -u postgres createdb -O "$db" "$db"
step "Events: configuration"
if [ ! -f "$app/backend/.env" ]; then
cat > "$app/backend/.env" <<ENV
NODE_ENV=production
PORT=$api
DATABASE_URL=postgresql://$db:$pass@localhost:5432/$db
JWT_SECRET=$(random_secret 64)
FRONTEND_URL=$url
APP_BASE_URL=$url
BACKEND_URL=$url
TRUST_PROXY=1
APP_TIMEZONE=Africa/Johannesburg
ENV
info "Wrote backend/.env (keep JWT_SECRET: it also encrypts stored secrets)."
else
info "backend/.env exists: kept."
fi
[ -f "$app/frontend/.env.production" ] || echo "NEXT_PUBLIC_API_URL=$url" > "$app/frontend/.env.production"
chown "$user:$user" "$app/backend/.env" "$app/frontend/.env.production"
chmod 600 "$app/backend/.env"
events_ensure_pm2_config "$dir" "$user"
step "Events: install, migrate, build"
events_install_deps "$dir" "$user"
events_migrate "$dir" "$user"
events_build "$dir" "$user"
step "Events: PM2"
run_as "$user" "$app" pm2 startOrReload ecosystem.config.js
run_as "$user" "$app" pm2 save
env PATH="$PATH:/usr/bin" pm2 startup systemd -u "$user" --hp "$(getent passwd "$user" | cut -d: -f6)" >/dev/null
step "Events: nginx ($domain)"
install_events_nginx "$name" "$domain" "$api" "$web"
if [ "$ssl" = 1 ]; then
step "Events: certificate"
certbot --nginx -d "$domain" --non-interactive --agree-tos -m "$email" --redirect
fi
step "Events: checking"
wait_for_version "$(events_health_url)" "$(events_expected_version "$dir")" 60 ||
warn "The backend isn't answering yet: sudo -u $user pm2 logs"
}
install_events_nginx() {
local name="$1" domain="$2" api="$3" web="$4"
# Only this domain is served by this site (no catch-all), as ROADMAP §8 asks.
cat > "/etc/nginx/sites-available/$name" <<NGINX
server {
listen 80;
server_name $domain;
client_max_body_size 25m;
# The API, uploaded files, health and API docs go to the backend; everything else to the site.
location ~ ^/(api|uploads|health|docs)(/|\$) {
proxy_pass http://127.0.0.1:$api;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
location / {
proxy_pass http://127.0.0.1:$web;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
}
NGINX
ln -sf "/etc/nginx/sites-available/$name" "/etc/nginx/sites-enabled/$name"
nginx -t
systemctl reload nginx
}
+89
View File
@@ -0,0 +1,89 @@
# shellcheck shell=bash
# crosscode status [<church>]: each product's version, latest release, health and last backup.
status_usage() {
cat <<'EOF'
crosscode status [<church>] [--no-fetch]
Each product's checked-out release, the latest release, and what /health reports (version,
database, jobs, last backup), for one church or every church on this server.
--no-fetch don't fetch tags first (faster; "latest" may be out of date)
EOF
}
cmd_status() {
local church="" fetch=1
while [ $# -gt 0 ]; do
case "$1" in
--no-fetch) fetch=0; shift ;;
-h|--help) status_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode status --help)." ;;
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
esac
done
require_root
local -a churches
if [ -n "$church" ]; then
churches=("$church")
else
mapfile -t churches < <(list_churches)
[ "${#churches[@]}" -gt 0 ] || { info "No churches on this server ($CROSSCODE_SITES/*/church.env)."; return 0; }
fi
local c
for c in "${churches[@]}"; do status_church "$c" "$fetch"; done
}
status_church() {
local church="$1" fetch="$2" p dir user ref latest url json version db jobs backup line
load_church "$church"
echo
step "$church ($(cenv ADDRESS '(no address)'))"
# shellcheck disable=SC2046 # PRODUCTS is a space-separated list of names
for p in $(in_product_order $(cenv PRODUCTS)); do
dir="$(pvar "$p" DIR)"
user="$(pvar "$p" USER)"
if [ ! -d "$dir/.git" ]; then
info "$(printf '%-9s %s' "$p" "missing checkout: $dir")"
continue
fi
if [ "$fetch" = 1 ]; then
run_as "$user" "$dir" timeout 20 git fetch --tags --quiet origin 2>/dev/null || true
fi
ref="$(checkout_ref "$dir" "$p")"
latest="$(latest_tag "$dir" "$p")"
line="$(printf '%-9s %-16s latest %-16s' "$p" "$ref" "${latest:-none}")"
[ -n "$latest" ] && [ "$ref" != "$latest" ] && line="$line (update available)"
info "$line"
if is_supported_product "$p"; then
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$p.sh"
url="$("${p}_health_url")"
if json="$(health_json "$url")"; then
version="$(printf '%s' "$json" | json_get version)"
db="$(printf '%s' "$json" | json_get db)"
jobs="$(printf '%s' "$json" | json_get jobs)"
backup="$(printf '%s' "$json" | json_get lastBackupAt)"
info " health: version ${version:-?}, database ${db:-?}, jobs ${jobs:-?}, last backup ${backup:-never}"
else
warn " $p isn't answering on $url (pm2 status; pm2 logs)."
fi
fi
status_old_folder "$p"
done
}
# After `adopt`, the old folder is kept for 14 days so `adopt --undo` can go back to it.
status_old_folder() {
local p="$1" old at age
old="$(pvar "$p" OLD_DIR)"
at="$(pvar "$p" ADOPTED_AT)"
[ -n "$old" ] && [ -d "$old" ] || return 0
age=$(( ($(date +%s) - $(date -d "$at" +%s 2>/dev/null || date +%s)) / 86400 ))
if [ "$age" -ge 14 ]; then
warn " The old folder $old is $age days old, past the 14 days kept for \`adopt --undo\`: remove it (rm -rf $old)."
else
info " Old folder kept for \`adopt --undo\`: $old (adopted $at, $((14 - age)) days left)."
fi
}
+79
View File
@@ -0,0 +1,79 @@
# shellcheck shell=bash
# Cross Events' hooks for the crosscode script (from hope-events' scripts/deploy.sh 2.1.x).
# Every hook takes the product's checkout (EVENTS_DIR, a checkout of crosscode-platform) and the
# app user, and runs the app's commands as that user. Values come from church.env (CENV).
#
# Adding a product means adding a file like this one with the same hooks, and its name in
# SUPPORTED_PRODUCTS (lib/common.sh).
events_app() { printf '%s/apps/events' "$1"; }
events_pm2_names() { pvar events PM2; }
events_pm2_config() { printf '%s/ecosystem.config.js' "$(events_app "$1")"; }
# EVENTS_PORTS="<api> <web>"
events_api_port() { local p; read -r p _ <<< "$(pvar events PORTS)"; printf '%s' "${p:-5000}"; }
events_web_port() { local p; read -r _ p <<< "$(pvar events PORTS)"; printf '%s' "${p:-3000}"; }
events_health_url() { printf 'http://127.0.0.1:%s/health' "$(events_api_port)"; }
# The version /health reports once this checkout runs (the backend's package.json).
events_expected_version() {
node -p 'require(process.argv[1]).version' "$(events_app "$1")/backend/package.json"
}
events_backup() {
local dir="$1" user="$2"
# shellcheck disable=SC2016
run_as "$user" "$(events_app "$dir")/backend" node -e '
require("dotenv").config();
require("./src/utils/backupUtils").runBackup()
.then(r => console.log(" " + r.filename))
.catch(e => { console.error(" Backup failed: " + e.message); process.exit(1); });'
}
# Only this app's workspaces, never the other products'. --include=dev: the TypeScript and Next
# builds need type and build packages even where NODE_ENV=production.
events_install_deps() {
run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend
}
events_migrate() {
run_as "$2" "$(events_app "$1")/backend" npm run prisma:deploy
}
events_pending_migrations() {
# prisma migrate status exits non-zero when migrations are pending (or the DB can't be read).
! run_as "$2" "$(events_app "$1")/backend" npx prisma migrate status >/dev/null 2>&1
}
events_build() {
run_as "$2" "$(events_app "$1")/backend" npm run build &&
run_as "$2" "$(events_app "$1")/frontend" npm run build
}
# After going back to the previous tag: install and build it again. Migrations aren't undone
# (the backup taken first has the database as it was).
events_rollback_build() {
events_install_deps "$1" "$2" && events_build "$1" "$2"
}
# The install's own PM2 config (not in git). Created from the example the first time, with this
# church's PM2 names and web port.
events_ensure_pm2_config() {
local dir="$1" user="$2" app conf backend frontend
app="$(events_app "$dir")"
conf="$app/ecosystem.config.js"
[ -f "$conf" ] && return 0
read -r backend frontend <<< "$(events_pm2_names)"
sed -e "s/'hope-events-backend'/'${backend}'/" \
-e "s/'hope-events-frontend'/'${frontend}'/" \
-e "s/-p 3000/-p $(events_web_port)/" \
"$app/ecosystem.config.example.js" > "$conf"
chown "$user:$user" "$conf" 2>/dev/null || true
info "Created $conf from the example."
}
events_reload() {
events_ensure_pm2_config "$1" "$2"
run_as "$2" "$(events_app "$1")" pm2 reload ecosystem.config.js --update-env
}
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bats
# adopt's helpers that don't need a server: rewriting the PM2 config, and finding the install's
# own data files. Run with `npm run test:scripts`.
setup() {
# shellcheck source=../lib/common.sh
source "$BATS_TEST_DIRNAME/../lib/common.sh"
# shellcheck source=../lib/adopt.sh
source "$BATS_TEST_DIRNAME/../lib/adopt.sh"
TMP="$BATS_TEST_TMPDIR"
}
@test "rewrite_ecosystem points absolute paths at the new app folder" {
run rewrite_ecosystem /var/www/hope-events /var/www/sites/hope/events/apps/events <<'EOF'
module.exports = { apps: [
{ name: 'hope-events-backend', cwd: '/var/www/hope-events/backend', script: 'src/index.js' },
{ name: 'hope-events-frontend', cwd: "/var/www/hope-events/frontend", script: 'npm', args: 'start -- -p 3000' },
{ name: 'x', cwd: `/var/www/hope-events`, out_file: '/var/www/hope-events2/log' },
] };
EOF
[[ "$output" == *"cwd: '/var/www/sites/hope/events/apps/events/backend'"* ]]
[[ "$output" == *'cwd: "/var/www/sites/hope/events/apps/events/frontend"'* ]]
[[ "$output" == *'cwd: `/var/www/sites/hope/events/apps/events`'* ]]
# A different folder that only starts the same isn't touched.
[[ "$output" == *"'/var/www/hope-events2/log'"* ]]
[[ "$output" == *"name: 'hope-events-backend'"* ]]
}
@test "rewrite_ecosystem leaves __dirname configs alone" {
input="$(cat "$BATS_TEST_DIRNAME/../../apps/events/ecosystem.config.example.js")"
run rewrite_ecosystem /var/www/hope-events /var/www/sites/hope/events/apps/events <<< "$input"
[ "$output" = "$input" ]
}
@test "rewrite_ecosystem copes with dots and other characters in paths" {
run rewrite_ecosystem /opt/hope.events /srv/a\&b <<'EOF'
cwd: '/opt/hope.events/backend', other: '/opt/hopexevents/backend'
EOF
[ "$output" = "cwd: '/srv/a&b/backend', other: '/opt/hopexevents/backend'" ]
}
@test "ignored_files_in lists the install's own data files, not tracked ones" {
git init -q "$TMP/old"
cd "$TMP/old"
mkdir -p backend/data
printf 'backend/data/banner.json\n' > .gitignore
echo '{}' > backend/data/defaults.json
git add . && git -c user.name=t -c user.email=t@t commit -q -m one
echo '{}' > backend/data/banner.json
run ignored_files_in "$TMP/old" backend/data
[ "$output" = "backend/data/banner.json" ]
}
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bats
# The crosscode entry script: help, and the argument checks that run before anything needs root.
setup() {
export CROSSCODE_NO_UPDATE=1
CC="$BATS_TEST_DIRNAME/../crosscode"
}
@test "help lists the commands" {
run bash "$CC" help
[ "$status" -eq 0 ]
[[ "$output" == *"crosscode deploy <church>"* ]]
[[ "$output" == *"crosscode adopt <church> --undo"* ]]
}
@test "help <command> shows that command's options" {
run bash "$CC" help deploy
[ "$status" -eq 0 ]
[[ "$output" == *"--every-church"* ]]
run bash "$CC" adopt --help
[ "$status" -eq 0 ]
[[ "$output" == *"--events-dir"* ]]
}
@test "an unknown command fails" {
run bash "$CC" frobnicate
[ "$status" -eq 1 ]
[[ "$output" == *'Unknown command "frobnicate"'* ]]
}
@test "the copy it runs from is removed afterwards" {
before="$(find /tmp -maxdepth 1 -name 'crosscode.*' 2>/dev/null | wc -l)"
run bash "$CC" help
after="$(find /tmp -maxdepth 1 -name 'crosscode.*' 2>/dev/null | wc -l)"
[ "$before" -eq "$after" ]
}
@test "deploy refuses bad arguments before touching anything" {
run bash "$CC" deploy hopefamily events --version events@2.2
[ "$status" -eq 1 ]
[[ "$output" == *"expected <product>@<x.y.z>"* ]]
run bash "$CC" deploy hopefamily --version events@2.2.0
[ "$status" -eq 1 ]
[[ "$output" == *"name events as well"* ]]
run bash "$CC" deploy hopefamily events --main --version events@2.2.0
[ "$status" -eq 1 ]
[[ "$output" == *"not both"* ]]
run bash "$CC" deploy hopefamily calendar
[ "$status" -eq 1 ]
[[ "$output" == *'Unknown product "calendar"'* ]]
run bash "$CC" deploy hopefamily --frobnicate
[ "$status" -eq 1 ]
run bash "$CC" deploy events --every-church
[ "$status" -eq 1 ]
[[ "$output" != *"doesn't take a church name"* ]]
run bash "$CC" deploy hopefamily --every-church
[ "$status" -eq 1 ]
[[ "$output" == *"doesn't take a church name"* ]]
}
@test "install and adopt check their arguments" {
run bash "$CC" install Hope --products events --domain hope.co.za --no-ssl
[ "$status" -eq 1 ]
[[ "$output" == *"isn't a church name"* ]]
run bash "$CC" install hope --products website --domain hope.co.za --no-ssl
[ "$status" -eq 1 ]
[[ "$output" == *"can only install events"* ]]
run bash "$CC" install hope --products events --domain hope.co.za
[ "$status" -eq 1 ]
[[ "$output" == *"--email is required"* ]]
run bash "$CC" adopt hope
[ "$status" -eq 1 ]
[[ "$output" == *"--events-dir is required"* ]]
run bash "$CC" adopt hope --events-dir /var/www/hope-events --version 2.2.0
[ "$status" -eq 1 ]
[[ "$output" == *"expected events@x.y.z"* ]]
}
+261
View File
@@ -0,0 +1,261 @@
#!/usr/bin/env bats
# The parts of the crosscode script that don't need a server: versions, tags, WHATS-NEW.md
# requirements, church.env and .env reading. Run with `npm run test:scripts`.
setup() {
# shellcheck source=../lib/common.sh
source "$BATS_TEST_DIRNAME/../lib/common.sh"
TMP="$BATS_TEST_TMPDIR"
}
# ── version_ge ──────────────────────────────────────────────────────────────────────────────
@test "version_ge compares x.y.z numerically" {
version_ge 1.2.0 1.2.0
version_ge 1.10.0 1.9.9
version_ge 2.0.0 1.99.99
run version_ge 1.9.0 1.10.0
[ "$status" -eq 1 ]
run version_ge 2.1.1 2.2.0
[ "$status" -eq 1 ]
}
@test "version_ge puts a prerelease below its release" {
version_ge 2.2.0 2.2.0-test
run version_ge 2.2.0-test 2.2.0
[ "$status" -eq 1 ]
version_ge 2.2.0-rc2 2.2.0-rc1
version_ge 2.2.0-test 2.1.9
}
@test "version_ge refuses something that isn't a version" {
run version_ge abc 1.0.0
[ "$status" -eq 2 ]
}
# ── tags ────────────────────────────────────────────────────────────────────────────────────
@test "latest_tag_from takes the newest release of that product only" {
run latest_tag_from events <<'EOF'
events@2.2.0
events@2.10.0
events@2.9.3
events@3.0.0-test
website@9.0.0
contracts@1.1.0
eventsx@4.0.0
EOF
[ "$status" -eq 0 ]
[ "$output" = "events@2.10.0" ]
}
@test "latest_tag_from is empty without releases" {
run latest_tag_from events <<'EOF'
events@2.2.0-test
contracts@1.0.0
EOF
[ "$output" = "" ]
}
@test "latest_tag and checkout_ref read a real checkout" {
git init -q "$TMP/repo"
cd "$TMP/repo"
git -c user.name=t -c user.email=t@t commit -q --allow-empty -m one
git tag events@2.2.0
git tag contracts@1.1.0
git -c user.name=t -c user.email=t@t commit -q --allow-empty -m two
git tag events@2.2.1
git tag events@2.3.0-test
[ "$(latest_tag "$TMP/repo" events)" = "events@2.2.1" ]
[ "$(checkout_ref "$TMP/repo" events)" = "events@2.2.1" ]
git checkout -q --detach events@2.2.0
[ "$(checkout_ref "$TMP/repo" events)" = "events@2.2.0" ]
git -c user.name=t -c user.email=t@t commit -q --allow-empty -m three
[ "$(checkout_ref "$TMP/repo" events)" = "$(git rev-parse --short HEAD)" ]
[ "$(tag_version events@2.2.1)" = "2.2.1" ]
}
# ── WHATS-NEW.md requirements ───────────────────────────────────────────────────────────────
whatsnew() {
cat <<'EOF'
# What's new in Cross Events
<!--
How this file is used: … Each version is a "## 1.2.3" heading; add "— urgent" …
## 9.9.9 — requires accounts 9.9.9
-->
## 3.1.0 — urgent — requires accounts 1.3.0, website v1.1.0
- Something.
## 3.0.0 — requires accounts 1.2.0
- Sign-in moves.
## [2.4.0] - 2026-12-01 — Requires Website 1.0.0 — urgent
## 2.3.0 — urgent
## 2.2.0
- Nothing changes for you.
EOF
}
@test "whatsnew_requires reads one requirement" {
run whatsnew_requires 3.0.0 < <(whatsnew)
[ "$output" = "accounts 1.2.0" ]
}
@test "whatsnew_requires reads several, after urgent and with a v prefix" {
run whatsnew_requires 3.1.0 < <(whatsnew)
[ "${lines[0]}" = "accounts 1.3.0" ]
[ "${lines[1]}" = "website 1.1.0" ]
[ "${#lines[@]}" -eq 2 ]
}
@test "whatsnew_requires ignores case, brackets, dates and a trailing urgent" {
run whatsnew_requires 2.4.0 < <(whatsnew)
[ "$output" = "website 1.0.0" ]
}
@test "whatsnew_requires is empty without requirements, or for a missing version" {
run whatsnew_requires 2.3.0 < <(whatsnew)
[ "$output" = "" ]
run whatsnew_requires 2.2.0 < <(whatsnew)
[ "$output" = "" ]
run whatsnew_requires 1.0.0 < <(whatsnew)
[ "$output" = "" ]
}
@test "whatsnew_requires skips headings inside HTML comments" {
run whatsnew_requires 9.9.9 < <(whatsnew)
[ "$output" = "" ]
}
@test "whatsnew_requires handles Windows line endings" {
run whatsnew_requires 3.0.0 < <(whatsnew | sed 's/$/\r/')
[ "$output" = "accounts 1.2.0" ]
}
@test "whatsnew_requires reads the real Cross Events notes" {
run whatsnew_requires 2.1.1 < "$BATS_TEST_DIRNAME/../../apps/events/WHATS-NEW.md"
[ "$status" -eq 0 ]
[ "$output" = "" ]
}
# ── church.env ──────────────────────────────────────────────────────────────────────────────
@test "church_env_read takes known keys, quoted or bare, and skips the rest" {
cat > "$TMP/church.env" <<'EOF'
# a comment
CHURCH=hopefamily
PRODUCTS="events website"
ADDRESS=hopefamily.co.za # the address
EVENTS_DIR=/var/www/sites/hopefamily/events
EVENTS_PM2='hope-events-backend hope-events-frontend'
EVENTS_PORTS="5000 3000" # api web
PATH=/tmp/evil
SOMETHING_ELSE=1
lower=1
EOF
church_env_read "$TMP/church.env"
[ "$(cenv CHURCH)" = hopefamily ]
[ "$(cenv PRODUCTS)" = "events website" ]
[ "$(cenv ADDRESS)" = hopefamily.co.za ]
[ "$(pvar events PM2)" = "hope-events-backend hope-events-frontend" ]
[ "$(pvar events PORTS)" = "5000 3000" ]
[ "$(pvar events DIR)" = /var/www/sites/hopefamily/events ]
[ -z "${CENV[PATH]+x}" ]
[ -z "${CENV[SOMETHING_ELSE]+x}" ]
[ "$PATH" != /tmp/evil ]
[ "$(pvar website DIR /fallback)" = /fallback ]
}
@test "church_env_read handles Windows line endings and fails on a missing file" {
printf 'CHURCH=grace\r\nEVENTS_DB=grace_events\r\n' > "$TMP/church.env"
church_env_read "$TMP/church.env"
[ "$(cenv CHURCH)" = grace ]
[ "$(pvar events DB)" = grace_events ]
run church_env_read "$TMP/missing.env"
[ "$status" -eq 1 ]
}
@test "church_env_write writes a fixed order that reads back the same" {
CENV=()
church_env_set EVENTS_PORTS "5000 3000"
church_env_set ADDRESS hopefamily.co.za
church_env_set EVENTS_DIR /var/www/sites/hopefamily/events
church_env_set ACCOUNTS_DIR /var/www/sites/hopefamily/accounts
church_env_set CHURCH hopefamily
church_env_set PRODUCTS "accounts events"
church_env_write "$TMP/church.env"
run grep -v '^#' "$TMP/church.env"
[ "${lines[0]}" = "CHURCH=hopefamily" ]
[ "${lines[1]}" = 'PRODUCTS="accounts events"' ]
[ "${lines[2]}" = "ADDRESS=hopefamily.co.za" ]
[ "${lines[3]}" = "ACCOUNTS_DIR=/var/www/sites/hopefamily/accounts" ]
[ "${lines[4]}" = "EVENTS_DIR=/var/www/sites/hopefamily/events" ]
[ "${lines[5]}" = 'EVENTS_PORTS="5000 3000"' ]
CENV=()
church_env_read "$TMP/church.env"
[ "$(cenv PRODUCTS)" = "accounts events" ]
[ "$(pvar events PORTS)" = "5000 3000" ]
[ "${#CENV[@]}" -eq 6 ]
}
@test "church_env_set refuses unknown keys and unsafe values" {
run church_env_set PATH /tmp
[ "$status" -eq 1 ]
run church_env_set EVENTS_DIR '/var/www/$(reboot)'
[ "$status" -eq 1 ]
run church_env_set EVENTS_DIR 'a"b'
[ "$status" -eq 1 ]
}
@test "list_churches lists folders with a church.env" {
CROSSCODE_SITES="$TMP/sites"
mkdir -p "$TMP/sites/hopefamily" "$TMP/sites/grace" "$TMP/sites/.undone-old"
touch "$TMP/sites/hopefamily/church.env" "$TMP/sites/grace/church.env"
run list_churches
[ "${#lines[@]}" -eq 2 ]
[[ "$output" == *hopefamily* ]]
[[ "$output" == *grace* ]]
}
@test "in_product_order puts products in deploy order, once each" {
run in_product_order app events accounts events
[ "${lines[0]}" = accounts ]
[ "${lines[1]}" = events ]
[ "${lines[2]}" = app ]
[ "${#lines[@]}" -eq 3 ]
}
@test "valid_slug" {
valid_slug hopefamily
valid_slug grace-church2
run valid_slug Hope
[ "$status" -eq 1 ]
run valid_slug ../etc
[ "$status" -eq 1 ]
run valid_slug 1church
[ "$status" -eq 1 ]
}
# ── .env and URLs ───────────────────────────────────────────────────────────────────────────
@test "env_value, db_name_from_url and host_from_url" {
cat > "$TMP/.env" <<'EOF'
# DATABASE_URL=postgresql://old
DATABASE_URL="postgresql://hope_events:p%40ss@localhost:5432/hope_events?schema=public"
PORT=5001
FRONTEND_URL=https://events.hopefamily.co.za,https://www.hopefamily.co.za
EOF
[ "$(env_value "$TMP/.env" PORT)" = 5001 ]
[ "$(env_value "$TMP/.env" MISSING)" = "" ]
[ "$(db_name_from_url "$(env_value "$TMP/.env" DATABASE_URL)")" = hope_events ]
[ "$(host_from_url "$(env_value "$TMP/.env" FRONTEND_URL)")" = events.hopefamily.co.za ]
[ "$(host_from_url http://localhost:3000/x)" = localhost ]
}
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env bats
# crosscode deploy against a local git "origin", with stub Events hooks that log what they do
# instead of running npm, Prisma or PM2. Covers the checks, requirements, order, rollback and
# --every-church. What needs a real server is tested on a VM (EVENTS-2.2-PLAN §6).
git_q() { git -c user.name=test -c user.email=test@test -c init.defaultBranch=main "$@"; }
setup() {
TMP="$BATS_TEST_TMPDIR"
export CROSSCODE_TEST=1 CROSSCODE_NO_UPDATE=1
export CROSSCODE_SITES="$TMP/sites"
export CROSSCODE_REPO="$TMP/origin"
export LOG="$TMP/log"
: > "$LOG"
# The crosscode script, with stub hooks for Events.
export CROSSCODE_HOME="$TMP/tools"
mkdir -p "$CROSSCODE_HOME/products"
cp -R "$BATS_TEST_DIRNAME/../lib" "$BATS_TEST_DIRNAME/../crosscode" "$CROSSCODE_HOME/"
cat > "$CROSSCODE_HOME/products/events.sh" <<'EOF'
ref() { git -C "$1" describe --tags --exact-match 2>/dev/null || echo main; }
events_backup() { echo "backup $(ref "$1")" >> "$LOG"; [ "${FAIL_AT:-}" != backup ]; }
events_install_deps() { echo "install $(ref "$1")" >> "$LOG"; }
events_migrate() { echo "migrate $(ref "$1")" >> "$LOG"; [ "${FAIL_AT:-}" != migrate ]; }
events_build() { echo "build $(ref "$1")" >> "$LOG"; [ "${FAIL_AT:-}" != build ]; }
events_rollback_build() { echo "rollback_build $(ref "$1")" >> "$LOG"; }
events_expected_version() { cat "$1/apps/events/VERSION"; }
events_reload() { echo "reload $(ref "$1")" >> "$LOG"; }
events_health_url() { echo http://stub/health; }
wait_for_version() { echo "health $2" >> "$LOG"; [ "${FAIL_HEALTH:-}" != "$2" ]; }
EOF
# origin: events@2.2.0, events@2.2.1, events@2.3.0 (which requires accounts 1.0.0).
git_q init -q "$TMP/origin"
mkdir -p "$TMP/origin/apps/events"
release 2.2.0 "## 2.2.0"
release 2.2.1 "## 2.2.1"
release 2.3.0 "## 2.3.0 — requires accounts 1.0.0"
add_church hope events@2.2.0
}
release() {
printf '%s\n' "$1" > "$TMP/origin/apps/events/VERSION"
printf '# What is new\n\n%s\n\n- Notes.\n' "$2" > "$TMP/origin/apps/events/WHATS-NEW.md"
git_q -C "$TMP/origin" add -A
git_q -C "$TMP/origin" commit -q -m "events $1"
git_q -C "$TMP/origin" tag "events@$1"
}
add_church() {
local church="$1" at="$2"
mkdir -p "$CROSSCODE_SITES/$church"
git_q clone -q "$CROSSCODE_REPO" "$CROSSCODE_SITES/$church/events"
git_q -C "$CROSSCODE_SITES/$church/events" checkout -q --detach "$at"
cat > "$CROSSCODE_SITES/$church/church.env" <<EOF
CHURCH=$church
PRODUCTS="events"
ADDRESS=$church.co.za
EVENTS_DIR=$CROSSCODE_SITES/$church/events
EVENTS_USER=$(id -un)
EVENTS_PM2="$church-events-backend $church-events-frontend"
EVENTS_PORTS="5000 3000"
EOF
}
on() { git -C "$CROSSCODE_SITES/$1/events" describe --tags --exact-match 2>/dev/null || echo main; }
cc() { bash "$CROSSCODE_HOME/crosscode" "$@"; }
@test "deploy --check refuses a release whose requirement isn't met, and changes nothing" {
run cc deploy hope events --check
[ "$status" -eq 1 ]
[[ "$output" == *"events 2.3.0 requires accounts 1.0.0"* ]]
[[ "$output" == *"Nothing was changed"* ]]
[ "$(on hope)" = events@2.2.0 ]
[ ! -s "$LOG" ]
}
@test "deploy to the latest release is refused while its requirement isn't met" {
run cc deploy hope events
[ "$status" -eq 1 ]
[[ "$output" == *"Requirements not met"* ]]
[ "$(on hope)" = events@2.2.0 ]
[ ! -s "$LOG" ]
}
@test "deploy --check with a met release says it's ready" {
run cc deploy hope events --check --version events@2.2.1
[ "$status" -eq 0 ]
[[ "$output" == *"events@2.2.0 → events@2.2.1"* ]]
[[ "$output" == *"ready to deploy"* ]]
[ ! -s "$LOG" ]
}
@test "deploy runs backup, checkout, install, migrate, build, reload and health, in that order" {
run cc deploy hope events --version events@2.2.1
[ "$status" -eq 0 ]
[ "$(on hope)" = events@2.2.1 ]
[ "$(cat "$LOG")" = "$(printf '%s\n' 'backup events@2.2.0' 'install events@2.2.1' 'migrate events@2.2.1' 'build events@2.2.1' 'reload events@2.2.1' 'health 2.2.1')" ]
[[ "$output" == *"updated events@2.2.0 → events@2.2.1"* ]]
}
@test "a church already on the release is left alone" {
run cc deploy hope events --version events@2.2.0
[ "$status" -eq 0 ]
[[ "$output" == *"already on events@2.2.0"* ]]
[ ! -s "$LOG" ]
}
@test "a failed backup changes nothing" {
FAIL_AT=backup run cc deploy hope events --version events@2.2.1
[ "$status" -eq 1 ]
[ "$(on hope)" = events@2.2.0 ]
[[ "$output" == *"failed at the backup"* ]]
run grep -q install "$LOG"
[ "$status" -ne 0 ]
}
@test "a failed migration goes back to the previous release, without reloading" {
FAIL_AT=migrate run cc deploy hope events --version events@2.2.1
[ "$status" -eq 1 ]
[ "$(on hope)" = events@2.2.0 ]
[[ "$output" == *"rolled back to events@2.2.0 (the running version was never stopped)"* ]]
grep -qx "rollback_build events@2.2.0" "$LOG"
run grep -q reload "$LOG"
[ "$status" -ne 0 ]
}
@test "a release that doesn't come up is rolled back, reloaded and checked again" {
FAIL_HEALTH=2.2.1 run cc deploy hope events --version events@2.2.1
[ "$status" -eq 1 ]
[ "$(on hope)" = events@2.2.0 ]
[ "$(grep -c reload "$LOG")" -eq 2 ]
grep -qx "health 2.2.0" "$LOG"
[[ "$output" == *"rolled back to events@2.2.0 and running again"* ]]
}
@test "files changed by hand stop the deploy" {
echo "hand edit" >> "$CROSSCODE_SITES/hope/events/apps/events/VERSION"
run cc deploy hope events --version events@2.2.1 --check
[ "$status" -eq 1 ]
[[ "$output" == *"changed or added by hand"* ]]
[[ "$output" == *"apps/events/VERSION"* ]]
run cc deploy hope events --version events@2.2.1
[ "$status" -eq 1 ]
[ ! -s "$LOG" ]
}
@test "--allow-local-changes deploys with a file added by hand" {
echo "notes" > "$CROSSCODE_SITES/hope/events/apps/events/notes.txt"
run cc deploy hope events --version events@2.2.1
[ "$status" -eq 1 ]
[ ! -s "$LOG" ]
run cc deploy hope events --version events@2.2.1 --allow-local-changes
[ "$status" -eq 0 ]
[[ "$output" == *"deploying anyway"* ]]
[ "$(on hope)" = events@2.2.1 ]
# --check never passes with changes, even with the flag.
run cc deploy hope events --check --allow-local-changes
[ "$status" -eq 1 ]
}
@test "ignored files (.env, ecosystem.config.js) don't count as changes" {
printf '.env\n/apps/events/ecosystem.config.js\n' > "$CROSSCODE_SITES/hope/events/.git/info/exclude"
echo "SECRET=1" > "$CROSSCODE_SITES/hope/events/.env"
echo "module.exports = {}" > "$CROSSCODE_SITES/hope/events/apps/events/ecosystem.config.js"
run cc deploy hope events --version events@2.2.1
[ "$status" -eq 0 ]
[ "$(on hope)" = events@2.2.1 ]
}
@test "a product the church doesn't have is refused; nothing named does nothing" {
run cc deploy hope website
[ "$status" -eq 1 ]
[[ "$output" == *"hope has no website"* ]]
run cc deploy hope
[ "$status" -eq 0 ]
[[ "$output" == *"Nothing to deploy"* ]]
}
@test "deploy --main checks out the latest main" {
release 2.4.0-dev "## 2.4.0-dev"
git_q -C "$TMP/origin" tag -d events@2.4.0-dev >/dev/null
run cc deploy hope events --main
[ "$status" -eq 0 ]
[ "$(on hope)" = main ]
grep -qx "health 2.4.0-dev" "$LOG"
}
@test "deploy --every-church updates each church, one after the other" {
add_church grace events@2.2.0
run cc deploy --every-church events --version events@2.2.1
[ "$status" -eq 0 ]
[ "$(on hope)" = events@2.2.1 ]
[ "$(on grace)" = events@2.2.1 ]
[ "$(grep -c '^health 2.2.1' "$LOG")" -eq 2 ]
}
@test "deploy --every-church stops at the first church that fails" {
add_church grace events@2.2.0
FAIL_AT=build run cc deploy --every-church events --version events@2.2.1
[ "$status" -eq 1 ]
[[ "$output" == *"Stopped at "* ]]
[ "$(grep -c '^backup' "$LOG")" -eq 1 ]
}
@test "unknown church" {
run cc deploy nowhere events
[ "$status" -eq 1 ]
[[ "$output" == *'No church "nowhere"'* ]]
}