Files
crosscode-platform/scripts/lib/manage.sh
T
joshuaandClaude Opus 5.5 8899c97a9c Agent 1.5.0 + contracts 1.16.0: uninstall, export and purge one product of a church
crosscode uninstall/export/purge <church> [product ...]: with products named only those
go and the church keeps the others; naming every product it still has removes the church
(folder and app user), so the last product to go takes the church with it. The report
gives products and remaining. Uninstalling cross-events-demo's Events removed its Accounts
too, which the Hub still showed as live.

Contracts 1.16.0: optional products on export/uninstall/purge, PRODUCT_UNINSTALL_MIN_AGENT.
Agent 1.5.0 passes them to crosscode. The Website plan moves to contracts 1.17.0 / Hub 2.13.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:17:32 +02:00

435 lines
19 KiB
Bash

# shellcheck shell=bash
# crosscode restart / export / uninstall / purge (docs/AGENT-1.0-PLAN.md §4 and §9).
CROSSCODE_REMOVED="${CROSSCODE_REMOVED:-$CROSSCODE_SITES/.removed}"
manage_usage() {
cat <<'EOF'
crosscode restart <church> [events] reload the products' PM2 processes
crosscode demo <church> --profile <profile> [--admin-email <email>]
replace Cross Events' data with a demo set
(small, events, ministry, multicampus); a backup
is taken first, one admin account is kept
crosscode env <church> <product> the product's .env values (secrets hidden)
crosscode env <church> <product> [--file backend/.env] --set NAME=value … [--unset NAME …] [--restart]
change values (a copy is kept; never secrets or
generated values). The frontend's file rebuilds it.
If it doesn't start again, the file is put back.
crosscode export <church> [product …] --out <file.zip>
the church's data (crosscode.church-export/1) and
uploads: every product, or only those named
crosscode uninstall <church> [product …] --confirm <church>
final backup and uploads kept in
/var/www/sites/.removed/<church>-<date>/ (30 days),
then PM2, tunnels, database and folders removed.
With products named only those go, and the church
keeps its others (naming every one = the church)
crosscode purge <church> [product …] --confirm <church>
delete what uninstall kept (with products named:
only what was kept of those)
All take --json (a report at the end; the log goes to stderr).
EOF
}
# The church's products that this script can handle, in deploy order.
manage_products() {
local p
# shellcheck disable=SC2046 # PRODUCTS is a space-separated list
for p in $(in_product_order $(cenv PRODUCTS)); do
is_supported_product "$p" && echo "$p"
done
return 0
}
# manage_check_named <product …>: stops unless the church (loaded) has each product named. Call it
# directly, not in $(…): die only stops the shell it runs in.
manage_check_named() {
local p
for p in "$@"; do
is_supported_product "$p" || die "Unknown product \"$p\" (this version handles: ${SUPPORTED_PRODUCTS[*]})."
church_has_product "$p" || die "$(cenv CHURCH) has no $p (its products: $(cenv PRODUCTS))."
done
}
# manage_named [product …]: those products in deploy order; none named: every product.
manage_named() {
if [ $# -gt 0 ]; then in_product_order "$@"; else manage_products; fi
}
cmd_restart() {
local church="" p
local -a named=()
while [ $# -gt 0 ]; do
case "$1" in
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help restart)." ;;
*) if [ -z "$church" ]; then church="$1"; else is_known_product "$1" || die "Unknown product \"$1\"."; named+=("$1"); fi; shift ;;
esac
done
[ -n "$church" ] || die "Name the church."
require_root
load_church "$church"
[ "${#named[@]}" -gt 0 ] || mapfile -t named < <(manage_products)
for p in "${named[@]}"; do
church_has_product "$p" || die "$church has no $p."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$p.sh"
step "$p: reloading PM2"
"${p}_reload" "$(pvar "$p" DIR)" "$(pvar "$p" USER)"
step "$p: waiting for it to answer"
wait_for_version "$("${p}_health_url")" "$("${p}_expected_version" "$(pvar "$p" DIR)")" 60
done
}
DEMO_PROFILES="small events ministry multicampus"
# Replaces Events' data with a demo set (apps/events/backend/scripts/set-demo.js), as the site's
# user (its .env is readable only by that user). The Hub sends it only for installs marked as demo
# sites. Afterwards Events is reloaded: the demo switches campuses on or off.
cmd_demo() {
local church="" profile="" email="" dir user app
while [ $# -gt 0 ]; do
case "$1" in
--profile) [ $# -ge 2 ] || die "--profile needs a value."; profile="$2"; shift 2 ;;
--admin-email) [ $# -ge 2 ] || die "--admin-email needs a value."; email="$2"; shift 2 ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help demo)." ;;
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
esac
done
[ -n "$church" ] || die "Name the church."
[[ " $DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $DEMO_PROFILES."
[ -z "$email" ] || [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || die "--admin-email: not an email address."
require_root
load_church "$church"
church_has_product events || die "$church has no Cross Events."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/events.sh"
dir="$(pvar events DIR)"
user="$(pvar events USER)"
app="$(events_app "$dir")"
[ -f "$app/backend/scripts/set-demo.js" ] || die "This release of Events ($(checkout_ref "$dir" events)) has no demo data."
step "Events: backup first"
events_backup "$dir" "$user" || die "The backup failed, so the demo data wasn't loaded."
step "Events: demo data ($profile)"
local -a env_args=()
# DEMO_ADMIN_EMAIL rather than --admin-email=: releases before 2.4.1 only read the variable.
[ -z "$email" ] || env_args=("DEMO_ADMIN_EMAIL=$email")
run_as "$user" "$app/backend" env "${env_args[@]+"${env_args[@]}"}" node scripts/set-demo.js "--profile=$profile" --yes ||
die "The demo data wasn't loaded (see above). If it got as far as changing anything, the backup from just now has the data from before."
step "Events: reloading PM2"
events_reload "$dir" "$user"
step "Events: waiting for it to answer"
wait_for_version "$(events_health_url)" "$(events_expected_version "$dir")" 60 ||
die "Events didn't answer after the reload (sudo -u $user pm2 logs)."
}
# crosscode env <church> <product>: the product's .env values, secrets hidden (the Hub's env-read).
# With --set / --unset (the Hub's env-set): changes one file (--file, default backend/.env), keeping
# a copy first; when the frontend's file changed, the frontend is rebuilt (Next.js builds its values
# in); then, with --restart or after a rebuild, the product is reloaded and must answer /health.
# Anything failing after the change puts the file back (and rebuilds again if it had rebuilt).
ENV_BACKUPS_KEPT=5
cmd_env() {
local church="" product="" file="backend/.env" restart=0 dir user app tpl path backup stamp out rc=0 rebuilt=0
local -a changes=()
while [ $# -gt 0 ]; do
case "$1" in
--file) [ $# -ge 2 ] || die "--file needs a value."; file="$2"; shift 2 ;;
--set|--unset) [ $# -ge 2 ] || die "$1 needs a value."; changes+=("$1" "$2"); shift 2 ;;
--restart) restart=1; shift ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help env)." ;;
*) if [ -z "$church" ]; then church="$1"; elif [ -z "$product" ]; then product="$1"; else die "Name one church and one product."; fi; shift ;;
esac
done
[ -n "$church" ] && [ -n "$product" ] || die "Name the church and the product (crosscode env hope events)."
[[ "$file" =~ ^(backend|frontend)/\.env(\.production)?$ ]] || die "--file: backend/.env or frontend/.env.production."
require_root
load_church "$church"
church_has_product "$product" || die "$church has no $product."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$product.sh"
dir="$(pvar "$product" DIR)"
user="$(pvar "$product" USER)"
app="$("${product}_app" "$dir")"
tpl="$(env_template "$app" "$product")"
if [ "${#changes[@]}" -eq 0 ]; then
step "$product: reading its .env files"
out="$(node "$CROSSCODE_HOME/lib/envedit.cjs" read --template "$tpl" --dir "$app" --product "$product")" || die "Couldn't read $product's .env files."
report_result_json env "$out"
# shellcheck disable=SC2016 # JavaScript template strings, not shell
[ "$CROSSCODE_JSON" = 1 ] || printf '%s\n' "$out" | node -e '
const r = JSON.parse(require("fs").readFileSync(0, "utf8"));
for (const f of r.files) {
console.log(`${f.file}${f.exists ? "" : " (missing)"}`);
for (const v of f.variables) console.log(` ${v.name}=${v.secret ? (v.set ? "(secret, set)" : "(secret, not set)") : (v.set ? v.value : "(not set)")}`);
}' >&2
return 0
fi
path="$app/$file"
[ -f "$path" ] || die "$church has no $product $file."
stamp="$(date -u +%Y%m%d%H%M%S)"
backup="$path.before-$stamp"
step "$product: changing $file (a copy is kept as $(basename "$backup"))"
out="$(node "$CROSSCODE_HOME/lib/envedit.cjs" set --template "$tpl" --dir "$app" --file "$file" --backup "$backup" "${changes[@]}")" || {
rm -f "$backup"
die "$product $file wasn't changed (see the message above)."
}
report_result_json changes "$out"
info "$out"
# Only the last few copies.
# shellcheck disable=SC2012 # names are ours: <file>.before-<digits>
ls -1t "$path".before-* 2>/dev/null | tail -n +$((ENV_BACKUPS_KEPT + 1)) | while read -r old; do rm -f -- "$old"; done
if [[ "$file" == frontend/* ]]; then
step "$product: rebuilding the frontend (it builds $file in)"
if run_as "$user" "$app/frontend" npm run build; then rebuilt=1; else rc=1; fi
fi
if [ "$rc" = 0 ] && { [ "$restart" = 1 ] || [ "$rebuilt" = 1 ]; }; then
step "$product: reloading PM2"
"${product}_reload" "$dir" "$user" || rc=1
if [ "$rc" = 0 ]; then
step "$product: waiting for it to answer"
wait_for_version "$("${product}_health_url")" "$("${product}_expected_version" "$dir")" 90 || rc=1
fi
fi
[ "$rc" = 0 ] && return 0
report_step_outcome failed
step "$product: putting $file back"
node "$CROSSCODE_HOME/lib/envedit.cjs" restore --file "$path" --backup "$backup" || die "Couldn't put $file back: the copy is $backup."
if [[ "$file" == frontend/* ]]; then
step "$product: rebuilding the frontend as it was"
run_as "$user" "$app/frontend" npm run build || die "The frontend didn't build again with the old $file: run npm run build in $app/frontend."
fi
if [ "$restart" = 1 ] || [[ "$file" == frontend/* ]]; then
step "$product: reloading PM2"
"${product}_reload" "$dir" "$user" || warn "PM2 reload failed: check pm2 status as $user."
wait_for_version "$("${product}_health_url")" "$("${product}_expected_version" "$dir")" 90 || true
fi
report_status rolled-back
die "$product didn't start with the new values, so $file was put back as it was."
}
# json_words <word …>: a JSON array of plain words (product names), e.g. ["accounts","events"].
json_words() {
local w out=""
for w in "$@"; do out+="${out:+,}\"$w\""; done
printf '[%s]' "$out"
}
cmd_export() {
local church="" out="" p tmp dir user bytes
local -a named=() products=()
while [ $# -gt 0 ]; do
case "$1" in
--out) [ $# -ge 2 ] || die "--out needs a file."; out="$2"; shift 2 ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help export)." ;;
*) if [ -z "$church" ]; then church="$1"; else named+=("$1"); fi; shift ;;
esac
done
[ -n "$church" ] || die "Name the church."
[[ "$out" == /*.zip ]] || die "--out: an absolute path ending in .zip."
[ ! -e "$out" ] || die "$out exists already."
require_root
load_church "$church"
manage_check_named "${named[@]}"
mapfile -t products < <(manage_named "${named[@]}")
[ "${#products[@]}" -gt 0 ] || die "$church has nothing to export."
command -v zip >/dev/null || die "zip isn't installed (apt-get install zip)."
tmp="$(mktemp -d)"
chmod 755 "$tmp"
local rc
set +e
(
set -e
for p in "${products[@]}"; do
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$p.sh"
dir="$(pvar "$p" DIR)"; user="$(pvar "$p" USER)"
step "$p: exporting the data"
mkdir -p "$tmp/$p"
chown "$user:$user" "$tmp/$p"
"${p}_export" "$dir" "$user" "$tmp/$p"
step "$p: adding the uploads"
"${p}_copy_uploads" "$dir" "$tmp/$p/uploads"
done
step "Zipping"
# One product: its folder is the ZIP's top level (export.json, uploads/, README.txt).
if [ "${#products[@]}" = 1 ]; then
(cd "$tmp/${products[0]}" && zip -qr "$out" .)
else
(cd "$tmp" && zip -qr "$out" .)
fi
chmod 600 "$out"
)
rc=$?
set -e
rm -rf "$tmp"
[ "$rc" = 0 ] || { rm -f "$out"; die "Export of $church failed."; }
bytes="$(stat -c %s "$out")"
report_result file "$out"
report_result_json bytes "$bytes"
report_result_json products "$(json_words "${products[@]}")"
step "Exported $church (${products[*]}) to $out ($bytes bytes)"
}
# uninstall_product <church> <product>: stops and removes one product, once its final backup is
# kept: PM2, frpc tunnels, nginx site, database, and the old folder from an adopt.
uninstall_product() {
local church="$1" p="$2" user db old name
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$p.sh"
user="$(pvar "$p" USER)"; db="$(pvar "$p" DB)"
step "$p: stopping and removing the PM2 processes"
# shellcheck disable=SC2046 # the PM2 names are a space-separated list
run_as "$user" / pm2 delete $("${p}_pm2_names") >/dev/null 2>&1 || true
run_as "$user" / pm2 save --force >/dev/null 2>&1 || true
if [ -f "$FRPC_INI" ] && frpc_has_block "$church" "$p"; then
step "$p: removing the frpc tunnels"
frpc_remove "$church" "$p"
frpc_reload
fi
name="$church-$p"
if [ -f "/etc/nginx/sites-available/$name" ]; then
step "$p: removing the nginx site"
rm -f "/etc/nginx/sites-enabled/$name" "/etc/nginx/sites-available/$name"
if nginx -t >/dev/null 2>&1; then systemctl reload nginx; else warn "nginx didn't reload: check nginx -t."; fi
fi
if [ -n "$db" ]; then
step "$p: dropping the database $db"
db_drop "$db"
fi
old="$(pvar "$p" OLD_DIR)"
if [ -n "$old" ] && [ -d "$old" ]; then rm -rf -- "$old"; info "Removed the old folder $old."; fi
}
cmd_uninstall() {
local church="" confirm="" p dir user kept key
local -a named=() products=() order=() left=()
while [ $# -gt 0 ]; do
case "$1" in
--confirm) [ $# -ge 2 ] || die "--confirm needs the church's name."; confirm="$2"; shift 2 ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help uninstall)." ;;
*) if [ -z "$church" ]; then church="$1"; else named+=("$1"); fi; shift ;;
esac
done
[ -n "$church" ] || die "Name the church."
[ "$confirm" = "$church" ] || die "Uninstalling removes $church's sites and databases: add --confirm $church."
require_root
load_church "$church"
manage_check_named "${named[@]}"
mapfile -t products < <(manage_named "${named[@]}")
# What the church keeps: every product of it not named (also ones this version can't handle).
for p in $(cenv PRODUCTS); do
[[ " ${products[*]} " == *" $p "* ]] || left+=("$p")
done
kept="$CROSSCODE_REMOVED/$church-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$kept"
chmod 700 "$CROSSCODE_REMOVED" "$kept"
report_result kept "$kept"
report_result_json products "$(json_words "${products[@]}")"
report_result_json remaining "$(json_words "${left[@]}")"
# 1. Keep a final backup, the uploads and the .env files (the backup needs JWT_SECRET to read
# stored secrets) for 30 days. Nothing is removed until this has worked for every product.
for p in "${products[@]}"; do
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/$p.sh"
dir="$(pvar "$p" DIR)"; user="$(pvar "$p" USER)"
step "$p: final backup"
"${p}_backup" "$dir" "$user"
step "$p: keeping the backup, uploads and settings in $kept/$p"
"${p}_keep" "$dir" "$kept/$p"
done
# 2. Remove, last product first.
mapfile -t order < <(printf '%s\n' "${products[@]}" | tac)
for p in "${order[@]}"; do uninstall_product "$church" "$p"; done
# 3a. The church keeps other products: only the removed ones' folders and church.env lines go.
if [ "${#left[@]}" -gt 0 ]; then
for p in "${order[@]}"; do
dir="$(pvar "$p" DIR)"
if [ -n "$dir" ] && [ "$(dirname "$dir")" = "$(church_dir "$church")" ] && [ -d "$dir" ]; then
step "$p: removing $dir"
rm -rf -- "$dir"
fi
for key in "${!CENV[@]}"; do
[[ "$key" == "$(upper "$p")_"* ]] && church_env_unset "$key"
done
done
church_env_set PRODUCTS "${left[*]}"
church_env_write "$(church_env_path "$church")"
step "Uninstalled ${products[*]} of $church, which keeps ${left[*]}. Kept until purged (30 days): $kept"
return 0
fi
# 3b. Nothing is left: the church goes.
step "Removing $(church_dir "$church")"
user="$(pvar events USER "$(pvar accounts USER)")"
rm -rf -- "$(church_dir "$church")"
# The app user goes too when crosscode made it for this church (cc-<church>).
if [ "$user" = "cc-$church" ] && id "$user" >/dev/null 2>&1; then
systemctl stop "pm2-$user" >/dev/null 2>&1 || true
pm2 unstartup systemd -u "$user" >/dev/null 2>&1 || true
pkill -u "$user" 2>/dev/null || true
userdel -r "$user" >/dev/null 2>&1 || warn "The user $user couldn't be removed (userdel -r $user)."
fi
step "Uninstalled $church. Kept until purged (30 days): $kept"
}
cmd_purge() {
local church="" confirm="" d p n=0
local -a named=()
while [ $# -gt 0 ]; do
case "$1" in
--confirm) [ $# -ge 2 ] || die "--confirm needs the church's name."; confirm="$2"; shift 2 ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help purge)." ;;
*) if [ -z "$church" ]; then church="$1"; else named+=("$1"); fi; shift ;;
esac
done
[ -n "$church" ] || die "Name the church."
valid_slug "$church" || die "\"$church\" isn't a church name."
for p in "${named[@]}"; do is_known_product "$p" || die "Unknown product \"$p\"."; done
[ "$confirm" = "$church" ] || die "Purging deletes $church's last backup for good: add --confirm $church."
require_root
if [ "${#named[@]}" -eq 0 ]; then
[ ! -f "$(church_env_path "$church")" ] || die "$church is still installed here; purge only deletes what uninstall kept (name the products that were uninstalled)."
elif church_env_read "$(church_env_path "$church")"; then
for p in "${named[@]}"; do
! church_has_product "$p" || die "$church still has $p here; purge only deletes what uninstall kept."
done
fi
for d in "$CROSSCODE_REMOVED/$church"-*; do
[ -d "$d" ] || continue
[[ "$(basename "$d")" =~ ^${church}-[0-9]{8}-[0-9]{6}$ ]] || continue
if [ "${#named[@]}" -eq 0 ]; then
step "Deleting $d"
rm -rf -- "$d"
n=$((n + 1))
continue
fi
for p in "${named[@]}"; do
[ -d "$d/$p" ] || continue
step "Deleting $d/$p"
rm -rf -- "${d:?}/$p"
n=$((n + 1))
done
rmdir -- "$d" 2>/dev/null || true
done
report_result_json deleted "$n"
[ "$n" -gt 0 ] || info "Nothing kept for $church${named[*]:+ (${named[*]})}."
}