zscripts-token-savers/bash/zbackup
KellyMichels 0054fe426b fix(bash): zbackup/zbackup_and_sync require an explicit target, matching PowerShell
Bare `zbackup` quietly backed up every project - inconsistent with the
PowerShell version (and with zdeploy), and an easy way to kick off a
huge unintended backup. Now a bare invocation prints usage and lists the
projects; `all` does what bare used to (every project + the scripts
folder). Same for `zbackup_and_sync`, and setup_backup_schedule's cron
line now passes `all` so the scheduled job still backs everything up.
2026-07-23 13:13:32 -05:00

152 lines
6.2 KiB
Bash

#!/usr/bin/env bash
# Evomedia.net Token Savers — https://github.com/kellymichels/zscripts-token-savers
# Created by Kelly Michels · dev@evomedia.net
# Licensed under the MIT License. See LICENSE.
#
# zbackup — local backups: zip project sources (plus a Postgres dump when the
# project's .env has a DATABASE_URL) into the backups folder.
#
# Usage:
# zbackup <project> [<project> ...]
# zbackup all # every project in zconfig.json + this scripts folder
# zbackup scripts # just this scripts folder ('scripts' is a reserved word)
# zbackup pyapp --tag "pre-migration"
#
# Output: <paths.backupsLocal>/<project>/<timestamp>_<project>[_tag].zip
set -uo pipefail
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/zhelpers.sh"
z_track_start "$@"
z_need_config
z_require zip
projects=(); tag=""
while [ $# -gt 0 ]; do
case "$1" in
--tag) tag="${2:-}"; shift 2 ;;
-*) err "Unknown option: $1"; exit 1 ;;
*) projects+=("$1"); shift ;;
esac
done
BACKUP_ROOT="$(z_path "$(zq '.paths.backupsLocal')")"
# Require an explicit target: bare invocation shows usage instead of quietly
# backing up everything - 'all' is explicit, matching zdeploy.
if [ "${#projects[@]}" -eq 0 ]; then
printf '\n'; warn "Usage: zbackup <project> [<project> ...] | all | scripts [--tag \"label\"]"
dim " Projects in zconfig.json: $(zproj_csv)"
dim " 'all' backs up every project plus this scripts folder; 'scripts' just this folder."
exit 1
fi
include_scripts=0
if printf '%s\n' "${projects[@]}" | grep -qx 'all'; then
projects=(); while IFS= read -r _zl || [ -n "$_zl" ]; do projects+=("$_zl"); done < <(zproj_keys)
include_scripts=1
else
filtered=()
for p in "${projects[@]}"; do
if [ "$p" = "scripts" ]; then include_scripts=1; else filtered+=("$p"); fi
done
projects=("${filtered[@]+"${filtered[@]}"}")
fi
ts() { date +%Y%m%d-%H%M%S; }
tag_suffix() { [ -n "$tag" ] && printf '_%s' "$(printf '%s' "$tag" | tr -s '[:space:]' '_')"; }
# Dump the project's Postgres database if its .env declares a DATABASE_URL.
# Checks <root>/.env, then <root>/backend/.env. Prints its own status line for
# every outcome; returns 0 (dumped, $2 written) or 1 (nothing dumped).
# A not-running database (connection refused) is a calm, expected skip; a real
# failure (version mismatch, auth, missing db) prints the loud pg_dump error.
local_pg_dump() { # <root> <out_path>
local root="$1" out="$2" env_file db_url err_out rc
env_file="$root/.env"; [ -f "$env_file" ] || env_file="$root/backend/.env"
if [ ! -f "$env_file" ]; then dim " No local DATABASE_URL - source-only backup."; return 1; fi
db_url="$(grep -m1 '^DATABASE_URL=' "$env_file" | cut -d= -f2- | tr -d '[:space:]')"
if [ -z "$db_url" ]; then dim " No local DATABASE_URL - source-only backup."; return 1; fi
db_url="$(printf '%s' "$db_url" | sed -E 's|^postgresql\+[^:]+://|postgresql://|')"
if [[ "$db_url" =~ ^postgresql://([^:]+):([^@]+)@([^:]+):([0-9]+)/([^?]+) ]]; then
local user="${BASH_REMATCH[1]}" pass="${BASH_REMATCH[2]}" host="${BASH_REMATCH[3]}"
local port="${BASH_REMATCH[4]}" db="${BASH_REMATCH[5]}"
command -v pg_dump >/dev/null 2>&1 || { err ' pg_dump not installed - skipping PG backup'; return 1; }
err_out="$(PGPASSWORD="$(z_urldecode "$pass")" pg_dump -h "$host" -p "$port" -U "$user" -d "$db" -F p -f "$out" 2>&1)"; rc=$?
if [ "$rc" -eq 0 ] && [ -f "$out" ]; then
ok " PostgreSQL dump: $(awk -v b="$(wc -c < "$out")" 'BEGIN{printf "%.1f", b/1024}') KB"
return 0
fi
# Not reachable (usually just not running locally) is expected - stay calm.
if printf '%s' "$err_out" | grep -qiE 'connection refused|could not connect|no route to host|could not translate host|timeout expired'; then
dim " Local database not running at $host:$port - source-only backup."
return 1
fi
# A real failure (version mismatch, auth, missing db) - show the reason.
err " pg_dump failed ($host:$port/$db as $user):"
printf '%s\n' "$err_out" | grep -v '^[[:space:]]*$' | sed 's/^/ /' >&2
return 1
fi
err ' Could not parse DATABASE_URL - skipping PG backup'
return 1
}
declare -a summary
exit_code=0
backup_project() { # <key>
local key="$1" root out_dir zip_path dump_dir db_dump extra="-"
zproj_require "$key"
root="$(zproj_root "$key")"
out_dir="$BACKUP_ROOT/$key"; mkdir -p "$out_dir"
zip_path="$out_dir/$(ts)_${key}$(tag_suffix).zip"
printf '\n'; info "=== [$(printf '%s' "$key" | tr '[:lower:]' '[:upper:]')] Local backup ($(zproj "$key" .label)) ==="
dim " Output: $zip_path"
[ -d "$root" ] || { err " Root not found: $root"; return 1; }
dump_dir="$(mktemp -d "${TMPDIR:-/tmp}/zbackup_${key}_XXXXXX")"
db_dump="$dump_dir/database_pg.sql"
warn " [1/3] Checking for a local database to dump..."
if local_pg_dump "$root" "$db_dump"; then extra="$db_dump"; fi
warn " [2/3] Archiving source..."
local excl=()
excl=(); while IFS= read -r _zl || [ -n "$_zl" ]; do excl+=("$_zl"); done < <(z_archive_excludes "$key" 1)
if ! z_archive "$root" "$zip_path" 0 "$extra" "${excl[@]}"; then
rm -rf "$dump_dir"; return 1
fi
rm -rf "$dump_dir"
warn " [3/3] Done."
summary+=("$key -> $zip_path ($(z_size_mb "$zip_path") MB)")
}
backup_scripts() {
local out_dir zip_path scripts_root
scripts_root="$(z_path "$(zq '.paths.scriptsRoot')")"
out_dir="$BACKUP_ROOT/scripts"; mkdir -p "$out_dir"
zip_path="$out_dir/$(ts)_scripts$(tag_suffix).zip"
printf '\n'; info "=== [SCRIPTS] Local backup (this scripts folder) ==="
dim " Output: $zip_path"
[ -d "$scripts_root" ] || { err " Scripts root not found: $scripts_root"; return 1; }
warn " [1/2] Archiving source..."
z_archive "$scripts_root" "$zip_path" 1 "-" .git archive tmp nul || return 1
warn " [2/2] Done."
summary+=("scripts -> $zip_path ($(z_size_mb "$zip_path") MB)")
}
for key in "${projects[@]+"${projects[@]}"}"; do
backup_project "$key" || { summary+=("$key -> FAILED"); exit_code=1; }
done
if [ "$include_scripts" -eq 1 ]; then
backup_scripts || { summary+=("scripts -> FAILED"); exit_code=1; }
fi
printf '\n'; info "=== Backup summary ==="
for line in "${summary[@]+"${summary[@]}"}"; do
case "$line" in *FAILED*) err " $line" ;; *) ok " $line" ;; esac
done
printf '\n'
exit "$exit_code"