#!/bin/sh
# Full-instance backups for a Docker Compose install of Sure.
#
# Runs as the `backup` service, from the same Sure image as web/worker (see
# compose.example.yml). A backup bundle holds everything needed to bring the
# same version back up elsewhere:
#
#   $BACKUP_DIR/<version>/<YYYY-MM-DD_HHMMSS>-<manual|scheduled>/
#     manifest.json    version, commit, image tags, schema version, ...
#     db.dump          pg_dump custom format
#     storage.tar.gz   the app-storage volume (uploaded files)
#     config/          the host's .env (contains secrets), compose file(s) and
#                      bin/sure-backup
#     restore.sh       restores the bundle into a new folder (see `recover`)
#     SHA256SUMS
#
# Usage (from the compose directory):
#   docker compose run --rm backup create [--version X] [--commit SHA]
#   docker compose run --rm backup list
#   docker compose run --rm backup restore <version/name | path | latest> [--yes] [--force] [--database-only]
#   docker compose run --rm backup prune
#
# With no arguments it runs `scheduled` (create + prune) every day at the time
# in BACKUP_SCHEDULE ("M H * * *", UTC). Off-site copies are made by the
# separate `backup-offsite` service.
#
# Or on the host, from the folder with compose.yml, without a backup service
# (works for any Sure version, including 0.7.5 and older):
#   sh sure-backup create | list | restore <backup> | prune
#
# To move the database to the PostgreSQL version in your compose file (for
# example 16 to 18), after updating the db image and volume mount there:
#   sh sure-backup upgrade-postgres [--yes] [--old-image IMAGE]
# It takes a backup first, keeps the old data, and restores into the new version.
#
# On the host, a bundle restores itself into a new project folder:
#   sh <bundle>/restore.sh [--target DIR] [--port N] [--with-worker | --without-worker] [--yes]
# which runs `sure-backup recover <bundle> ...`. It needs Docker with Compose.
set -e

# shellcheck disable=SC3040
if (set -o pipefail 2>/dev/null); then
  set -o pipefail
fi

BACKUP_DIR=${BACKUP_DIR_IN_CONTAINER:-/backups}
STORAGE_DIR=${SURE_STORAGE_DIR:-/rails/storage}
CONFIG_DIR=${SURE_CONFIG_DIR:-/config}
STAMP_FILE="${STORAGE_DIR}/.sure-runtime"
IMAGE_REPO=${SURE_IMAGE_REPO:-ghcr.io/we-promise/sure}

BACKUP_SCHEDULE=${BACKUP_SCHEDULE:-0 2 * * *}
BACKUP_KEEP_DAYS=${BACKUP_KEEP_DAYS:-7}
INSTANCE_ID=${INSTANCE_ID:-default}
POSTGRES_PORT=${POSTGRES_PORT:-5432}

log() { echo "[sure-backup] $*"; }
warn() { echo "[sure-backup] WARNING: $*" >&2; }
die() { echo "[sure-backup] ERROR: $*" >&2; exit 1; }

usage() {
  awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"
}

# on_exit COMMAND: run COMMAND when the script ends. A signal handler that
# returns lets sh carry on with the next command, so INT and TERM exit, which
# runs COMMAND through the EXIT trap. Callers single-quote COMMAND so that its
# variables expand when it runs.
on_exit() {
  # shellcheck disable=SC2064
  trap "$1" EXIT
  trap 'exit 130' INT TERM
}

# Eight random hex characters, for names that must not collide between runs.
# $$ cannot do it: in a container the script is often PID 1 every time.
random_suffix() {
  od -An -N4 -tx1 /dev/urandom | tr -d ' \n'
}

# --- setup -------------------------------------------------------------------

ensure_deps() {
  # The Sure image has all of these. The apk fallback keeps Alpine-based
  # backup services from v0.7.5 working.
  missing=""
  if ! command -v pg_dump >/dev/null 2>&1; then
    # Take the newest client this Alpine release has: pg_dump must be at
    # least as new as the server, and pg_restore as new as the dump.
    pg_pkg="postgresql16-client~=16"
    for v in 18 17; do
      if apk search -q "postgresql${v}-client" 2>/dev/null | grep -qx "postgresql${v}-client"; then
        pg_pkg="postgresql${v}-client"
        break
      fi
    done
    missing="$missing $pg_pkg"
  fi
  # BusyBox tar lacks --numeric-owner/--exclude semantics we rely on.
  tar --version 2>/dev/null | grep -q "GNU tar" || missing="$missing tar~=1"
  [ -z "$missing" ] && return 0

  command -v apk >/dev/null 2>&1 || die "missing tools (${missing# }) and no apk to install them"
  log "Installing:${missing}"
  # shellcheck disable=SC2086
  if ! apk_out=$(apk add --no-cache --quiet $missing 2>&1); then
    echo "$apk_out" >&2
    die "could not install required packages"
  fi
}

check_db_env() {
  if [ -z "$POSTGRES_DB" ] || [ -z "$POSTGRES_USER" ] || [ -z "$POSTGRES_PASSWORD" ] || [ -z "$POSTGRES_HOST" ]; then
    die "database connection variables are not fully set"
  fi

  case "${POSTGRES_HOST}${POSTGRES_PORT}${POSTGRES_DB}${POSTGRES_USER}${POSTGRES_PASSWORD}" in
    *"
"*)
      die "database connection parameters must not contain newlines"
      ;;
  esac
}

check_keep_days() {
  if ! [ "$BACKUP_KEEP_DAYS" -gt 0 ] 2>/dev/null; then
    die "BACKUP_KEEP_DAYS must be a positive integer (got: ${BACKUP_KEEP_DAYS})"
  fi
}

# Write a .pgpass with escaped fields so the password never hits argv.
setup_pgpass() {
  WORK_DIR=$(umask 077 && mktemp -d)
  # shellcheck disable=SC2016
  on_exit 'rm -rf "${WORK_DIR}"'

  pg_esc() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/:/\\:/g'; }

  # "*" for the database so dropdb/createdb can use the maintenance database.
  (umask 077 && printf '%s:%s:*:%s:%s\n' \
    "$(pg_esc "$POSTGRES_HOST")" "$(pg_esc "$POSTGRES_PORT")" \
    "$(pg_esc "$POSTGRES_USER")" "$(pg_esc "$POSTGRES_PASSWORD")" > "${WORK_DIR}/.pgpass")
  export PGPASSFILE="${WORK_DIR}/.pgpass"
  export PGHOST="$POSTGRES_HOST" PGPORT="$POSTGRES_PORT" PGUSER="$POSTGRES_USER"
}

psql_value() {
  psql -X -q -t -A -v ON_ERROR_STOP=1 -d "${2:-$POSTGRES_DB}" -c "$1"
}

json_str() {
  printf '"%s"' "$(printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
}

manifest_value() {
  sed -n "s/^[[:space:]]*\"$2\": \"\([^\"]*\)\".*/\1/p" "$1/manifest.json" | head -n 1
}

# The Sure image ships an empty /rails/storage, so "is a directory" is not
# enough: the uploaded-files volume must actually be mounted there.
storage_mounted() {
  [ -d "$STORAGE_DIR" ] && awk -v d="$STORAGE_DIR" '$2 == d { found = 1 } END { exit !found }' /proc/mounts 2>/dev/null
}

stamp_value() {
  sed -n "s/^$1=//p" "$STAMP_FILE" 2>/dev/null | head -n 1
}

# --- create ------------------------------------------------------------------

cmd_create() {
  trigger=manual
  version=""
  commit=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --version) version=$2; shift 2 ;;
      --commit) commit=$2; shift 2 ;;
      --scheduled) trigger=scheduled; shift ;;
      --pre-upgrade) trigger=pre-upgrade; shift ;;
      *) die "unknown option for create: $1" ;;
    esac
  done

  check_db_env
  ensure_deps
  setup_pgpass

  # pg_dump refuses servers newer than itself; say what to do about it.
  server_major=$(( $(psql_value "SHOW server_version_num") / 10000 ))
  dump_client_major=$(pg_dump --version | sed -n 's/.* \([0-9][0-9]*\)\..*/\1/p')
  if [ "$server_major" -gt "${dump_client_major:-0}" ]; then
    die "the database server is PostgreSQL ${server_major}, but this Sure version ships pg_dump ${dump_client_major:-?}, which cannot back up newer servers. Upgrade Sure to a version that supports PostgreSQL ${server_major}."
  fi

  db_schema=$(psql_value "SELECT max(version) FROM schema_migrations" 2>/dev/null) \
    || die "cannot read schema_migrations from ${POSTGRES_DB}; is the database initialized?"

  # The web container stamps the version that migrated the database. Trust it
  # only if the database is still at that schema, otherwise the stamp is stale
  # (e.g. the image was swapped but web has not booted the new one yet).
  if [ -f "$STAMP_FILE" ]; then
    stamp_version=$(stamp_value SURE_VERSION)
    stamp_schema=$(stamp_value SURE_SCHEMA_VERSION)
    if [ -n "$version" ] && [ "$version" != "$stamp_version" ]; then
      die "--version ${version} disagrees with the running app (${stamp_version}); drop --version"
    fi
    if [ "$stamp_schema" != "$db_schema" ]; then
      die "database schema ${db_schema} does not match the app's stamped schema ${stamp_schema} (version ${stamp_version}). Start the web service so it re-stamps, then retry."
    fi
    version=$stamp_version
    commit=${commit:-$(stamp_value SURE_COMMIT)}
  elif [ -z "$version" ] && [ -f /rails/.sure-version ] && [ -f /rails/db/schema.rb ]; then
    # Running in a Sure image that predates stamping: use the image's own
    # version, but only if the database is at that version's schema.
    image_version=$(tr -d '[:space:]' < /rails/.sure-version)
    image_schema=$(sed -n 's/.*define(version: \([0-9_]*\)).*/\1/p' /rails/db/schema.rb | tr -d _)
    if [ "$image_schema" != "$db_schema" ]; then
      die "database schema ${db_schema} does not match this image (Sure ${image_version}, schema ${image_schema}). Run the backup with the image the app runs on, or pass --version."
    fi
    version=$image_version
    commit=${commit:-${BUILD_COMMIT_SHA:-}}
    log "No version stamp; using this image's version ${version} (database schema matches)"
  elif [ -z "$version" ]; then
    die "no version stamp at ${STAMP_FILE} (app image predates stamping). Pass --version, e.g. --version 0.7.4"
  else
    warn "no version stamp; trusting --version ${version}"
  fi

  case "$version" in
    "" | *[!A-Za-z0-9._+-]*) die "invalid version: ${version}" ;;
  esac

  name="$(date -u +%Y-%m-%d_%H%M%S)-${trigger}"
  final_dir="${BACKUP_DIR}/${version}/${name}"
  [ -e "$final_dir" ] && die "${final_dir} already exists"

  tmp_dir="${BACKUP_DIR}/.tmp-${name}-$$"
  mkdir -p "$BACKUP_DIR"
  (umask 077 && mkdir -p "${tmp_dir}/config")
  # shellcheck disable=SC2016
  on_exit 'rm -rf "${WORK_DIR}" "${tmp_dir}"'

  log "Backing up Sure ${version} to ${version}/${name}"

  log "Dumping database ${POSTGRES_DB}..."
  (umask 077 && pg_dump -Fc -d "$POSTGRES_DB" -f "${tmp_dir}/db.dump")

  storage_service=""
  if [ -f "${CONFIG_DIR}/.env" ]; then
    storage_service=$(sed -n 's/^ACTIVE_STORAGE_SERVICE=//p' "${CONFIG_DIR}/.env" | tail -n 1 | tr -d '"'"'"' ')
  fi
  case "$storage_service" in
    "" | local) ;;
    *) warn "uploaded files are stored in '${storage_service}' (ACTIVE_STORAGE_SERVICE), not in this backup" ;;
  esac

  if storage_mounted; then
    log "Archiving file storage..."
    (umask 077 && tar -C "$STORAGE_DIR" --numeric-owner --exclude=./.sure-runtime -czf "${tmp_dir}/storage.tar.gz" .)
  else
    warn "${STORAGE_DIR} is not mounted; uploaded files are NOT included"
  fi

  if [ -f "${CONFIG_DIR}/.env" ]; then
    cp "${CONFIG_DIR}/.env" "${tmp_dir}/config/.env"
  else
    warn "no .env in ${CONFIG_DIR}; it is NOT included"
  fi
  for f in compose.yml compose.yaml docker-compose.yml docker-compose.yaml; do
    [ -f "${CONFIG_DIR}/${f}" ] || continue
    cp "${CONFIG_DIR}/${f}" "${tmp_dir}/config/${f}"
    compose_found=true
  done
  [ "${compose_found:-}" = true ] || warn "no compose file in ${CONFIG_DIR}; it is NOT included"
  for f in compose.override.yml compose.override.yaml docker-compose.override.yml docker-compose.override.yaml; do
    [ -f "${CONFIG_DIR}/${f}" ] && cp "${CONFIG_DIR}/${f}" "${tmp_dir}/config/${f}"
  done
  find "${tmp_dir}/config" -type f -exec chmod 0600 {} +
  # This script and an entry point for it, so a bundle restores on its own.
  mkdir -p "${tmp_dir}/config/bin"
  cp "$0" "${tmp_dir}/config/bin/sure-backup"
  chmod 0755 "${tmp_dir}/config/bin/sure-backup"
  cat > "${tmp_dir}/restore.sh" <<'EOF'
#!/bin/sh
# Restores this backup into a new folder as a separate Sure instance.
# Run it with: sh restore.sh   (needs Docker with Compose; --help for options)
dir=$(cd "$(dirname "$0")" && pwd)
exec sh "$dir/config/bin/sure-backup" recover "$dir" "$@"
EOF
  chmod 0755 "${tmp_dir}/restore.sh"

  pg_server=$(psql_value "SHOW server_version")
  if [ -n "$commit" ]; then
    commit_json=$(json_str "$commit")
    image_by_commit_json=$(json_str "${IMAGE_REPO}:sha-${commit}")
  else
    commit_json=null
    image_by_commit_json=null
  fi
  # One key per line: manifest_value reads it back with sed.
  {
    echo "{"
    echo "  \"format\": 1,"
    echo "  \"sure_version\": $(json_str "$version"),"
    echo "  \"sure_commit\": ${commit_json},"
    echo "  \"image\": $(json_str "${IMAGE_REPO}:${version}"),"
    echo "  \"image_by_commit\": ${image_by_commit_json},"
    echo "  \"schema_version\": $(json_str "$db_schema"),"
    echo "  \"created_at\": $(json_str "$(date -u +%Y-%m-%dT%H:%M:%SZ)"),"
    echo "  \"trigger\": $(json_str "$trigger"),"
    echo "  \"instance_id\": $(json_str "$INSTANCE_ID"),"
    echo "  \"database\": $(json_str "$POSTGRES_DB"),"
    echo "  \"postgres_server_version\": $(json_str "$pg_server"),"
    echo "  \"pg_dump_version\": $(json_str "$(pg_dump --version)")"
    echo "}"
  } > "${tmp_dir}/manifest.json"

  (cd "$tmp_dir" && find . -type f | sort | xargs sha256sum > "${WORK_DIR}/SHA256SUMS")
  mv "${WORK_DIR}/SHA256SUMS" "${tmp_dir}/SHA256SUMS"

  mkdir -p "${BACKUP_DIR}/${version}"
  mv "$tmp_dir" "$final_dir"
  log "Done: ${final_dir} ($(du -sh "$final_dir" | cut -f1))"
  # For upgrade-postgres, which restores exactly this bundle.
  [ -z "${SURE_RESULT_FILE:-}" ] || printf '%s\n' "${version}/${name}" > "$SURE_RESULT_FILE"
}

# --- list --------------------------------------------------------------------

bundles() {
  # Newest first; the directory name starts with a sortable UTC timestamp.
  find "$BACKUP_DIR" -mindepth 3 -maxdepth 3 -name manifest.json ! -path '*/.tmp-*' 2>/dev/null \
    | while read -r m; do
        d=$(dirname "$m")
        printf '%s\t%s\n' "$(basename "$d")" "$d"
      done | sort -r | cut -f2
}

cmd_list() {
  found=$(bundles)
  if [ -z "$found" ]; then
    log "No backups in ${BACKUP_DIR}"
    return 0
  fi
  printf '%-40s %-10s %-8s %s\n' "BACKUP" "TRIGGER" "SIZE" "IMAGE"
  echo "$found" | while read -r d; do
    printf '%-40s %-10s %-8s %s\n' \
      "${d#"${BACKUP_DIR}"/}" \
      "$(manifest_value "$d" trigger)" \
      "$(du -sh "$d" | cut -f1)" \
      "$(manifest_value "$d" image)"
  done
}

# --- restore -----------------------------------------------------------------

resolve_bundle() {
  case "$1" in
    "") die "restore needs a backup id (see 'list'), a path, or 'latest'" ;;
    latest) dir=$(bundles | head -n 1) ;;
    /*) dir=$1 ;;
    *) dir="${BACKUP_DIR}/$1" ;;
  esac
  [ -n "$dir" ] && [ -f "${dir}/manifest.json" ] || die "no backup found at ${dir:-$1}"
  echo "$dir"
}

env_secret_hash() {
  [ -f "$1" ] || return 0
  sed -n 's/^SECRET_KEY_BASE=//p' "$1" | tail -n 1 | sha256sum | cut -c1-16
}

sql_literal() {
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/''/g")"
}

sql_ident() {
  printf '"%s"' "$(printf '%s' "$1" | sed 's/"/""/g')"
}

# load_dump DATABASE DUMP: uses client_major and server_major from cmd_restore.
load_dump() {
  if [ "$client_major" -le "$server_major" ]; then
    pg_restore --no-owner --role="$POSTGRES_USER" --exit-on-error -d "$1" "$2"
    return $?
  fi
  # A newer pg_restore emits settings an older server rejects (e.g.
  # transaction_timeout, new in 17), so restore through SQL without them.
  # Only the settings block at the top is filtered (it ends at the first other
  # statement); table data could hold the same text.
  pg_restore --no-owner --role="$POSTGRES_USER" -f "${WORK_DIR}/restore.sql" "$2" || return 1
  load_status=0
  awk 'BEGIN { header = 1 }
    header && /^[A-Za-z]/ && !/^(SET |SELECT pg_catalog\.set_config)/ { header = 0 }
    header && /^SET transaction_timeout = / { next }
    { print }' "${WORK_DIR}/restore.sql" \
    | psql -X -q -v ON_ERROR_STOP=1 -d "$1" >/dev/null || load_status=$?
  rm -f "${WORK_DIR}/restore.sql"
  return "$load_status"
}

cmd_restore() {
  target=""
  assume_yes=false
  force=false
  database_only=false
  while [ $# -gt 0 ]; do
    case "$1" in
      --yes) assume_yes=true; shift ;;
      --force) force=true; shift ;;
      --database-only) database_only=true; shift ;;
      -*) die "unknown option for restore: $1" ;;
      *) target=$1; shift ;;
    esac
  done

  check_db_env
  ensure_deps
  dir=$(resolve_bundle "$target")
  setup_pgpass
  # Administration connects elsewhere: PostgreSQL cannot rename or close the
  # database a session is connected to.
  maint_db=postgres
  [ "$POSTGRES_DB" != postgres ] || maint_db=template1

  log "Verifying checksums..."
  (cd "$dir" && sha256sum -c SHA256SUMS >/dev/null) || die "checksum verification failed for ${dir}"

  version=$(manifest_value "$dir" sure_version)
  image=$(manifest_value "$dir" image)
  image_by_commit=$(manifest_value "$dir" image_by_commit)

  # pg_restore can't read dumps made by a newer pg_dump; say so plainly.
  dump_major=$(manifest_value "$dir" pg_dump_version | sed -n 's/.* \([0-9][0-9]*\)\..*/\1/p')
  client_major=$(pg_restore --version | sed -n 's/.* \([0-9][0-9]*\)\..*/\1/p')
  case "$client_major" in "" | *[!0-9]*) die "cannot read the pg_restore version" ;; esac
  case "$dump_major" in *[!0-9]*) dump_major="" ;; esac
  if [ -n "$dump_major" ] && [ "$dump_major" -gt "$client_major" ]; then
    die "this backup was made with pg_dump ${dump_major}, but this pg_restore is ${client_major}. Restore it from the host with 'sh sure-backup restore', which runs in the Sure image, or with PostgreSQL ${dump_major} client tools."
  fi

  # Checked up front so a missing mount can't leave a half-restored instance.
  if [ "$database_only" != true ] && [ -f "${dir}/storage.tar.gz" ] && ! storage_mounted; then
    die "${STORAGE_DIR} is not mounted; cannot restore uploaded files"
  fi

  others=$(psql_value "SELECT count(*) FROM pg_stat_activity WHERE datname = '${POSTGRES_DB}' AND pid <> pg_backend_pid()" "$maint_db")
  if [ "$others" -gt 0 ] && [ "$force" != true ]; then
    die "${others} other connection(s) to ${POSTGRES_DB}. Stop the app first: docker compose stop web worker (or pass --force)"
  fi

  if [ "$assume_yes" != true ]; then
    if [ -t 0 ]; then
      what="database ${POSTGRES_DB}"
      [ "$database_only" = true ] || what="${what} and all uploaded files"
      printf 'This REPLACES %s with %s. Type "restore" to continue: ' "$what" "${dir#"${BACKUP_DIR}"/}"
      read -r answer
      [ "$answer" = "restore" ] || die "aborted"
    else
      die "refusing to restore without a TTY; pass --yes"
    fi
  fi

  server_major=$(( $(psql_value "SHOW server_version_num" "$maint_db") / 10000 ))
  backup_major=$(manifest_value "$dir" postgres_server_version | sed -n 's/^\([0-9][0-9]*\).*/\1/p')
  if [ -n "$backup_major" ] && [ "$backup_major" -gt "$server_major" ]; then
    warn "this backup comes from PostgreSQL ${backup_major}. Restoring it into PostgreSQL ${server_major} usually works but is not guaranteed; ${POSTGRES_DB} is only replaced if it loads cleanly."
  fi

  # Load into a scratch database and swap it in only once it has loaded, so a
  # failed restore leaves the current database as it was.
  # Not derived from POSTGRES_DB: PostgreSQL truncates names to 63 bytes, which
  # could turn a suffixed name back into the live database's.
  scratch_db="sure_restore_$(random_suffix)"
  [ "$scratch_db" != "$POSTGRES_DB" ] || die "the database is named like a restore scratch database (${POSTGRES_DB}); rename it first"
  log "Restoring database..."
  # createdb fails if the name is taken, so another run's database is never touched.
  createdb --maintenance-db="$maint_db" -O "$POSTGRES_USER" "$scratch_db"
  # The scratch copy is not kept on failure: the bundle can load it again.
  discard_scratch() { dropdb --maintenance-db="$maint_db" --if-exists --force "$scratch_db" || true; }
  if ! load_dump "$scratch_db" "${dir}/db.dump"; then
    discard_scratch
    die "the database restore failed; ${POSTGRES_DB} was left as it was"
  fi

  # Swap by renaming: set the current database aside, give the restored one
  # its name, and only then drop the old one. At every point both copies
  # exist under some name, and a failure puts the current database back.
  log "Replacing database ${POSTGRES_DB}..."
  previous_db="sure_replaced_$(random_suffix)"
  admin_sql() { psql -X -q -v ON_ERROR_STOP=1 -d "$maint_db" -c "$1" >/dev/null; }
  rename_db() { admin_sql "ALTER DATABASE $(sql_ident "$1") RENAME TO $(sql_ident "$2")"; }
  set_connections() { admin_sql "ALTER DATABASE $(sql_ident "$1") WITH ALLOW_CONNECTIONS $2"; }
  reopen_hint="ALTER DATABASE \"${POSTGRES_DB}\" WITH ALLOW_CONNECTIONS true"
  # abort_swap MESSAGE: once the live database is closed, but before it is
  # renamed, every failure reopens it and leaves it as it was.
  abort_swap() {
    set_connections "$POSTGRES_DB" true || warn "could not reopen ${POSTGRES_DB} to connections; run: ${reopen_hint}"
    discard_scratch
    die "$1; ${POSTGRES_DB} was left as it was"
  }
  live_exists=$(psql_value "SELECT count(*) FROM pg_database WHERE datname = $(sql_literal "$POSTGRES_DB")" "$maint_db")
  swap_interrupted() {
    warn "interrupted while replacing ${POSTGRES_DB}. No data was lost: the previous database may now be named ${previous_db}, and the restored one ${scratch_db} or ${POSTGRES_DB}. Run the restore again, or rename the one you want with: ALTER DATABASE \"<name>\" RENAME TO \"${POSTGRES_DB}\"; ${reopen_hint}"
    rm -rf "${WORK_DIR}"
    exit 1
  }
  trap swap_interrupted INT TERM

  if [ "$live_exists" -gt 0 ]; then
    # Close the database to new sessions before counting the open ones, so
    # none can connect between the check and the rename.
    if ! set_connections "$POSTGRES_DB" false; then
      discard_scratch
      die "could not close ${POSTGRES_DB} to new connections; it was left as it was"
    fi
    others=$(psql_value "SELECT count(*) FROM pg_stat_activity WHERE datname = $(sql_literal "$POSTGRES_DB")" "$maint_db") \
      || abort_swap "could not count the connections to ${POSTGRES_DB}"
    if [ "$others" -gt 0 ] && [ "$force" != true ]; then
      abort_swap "${others} connection(s) to ${POSTGRES_DB} were opened during the restore. Stop the app (docker compose stop web worker) and run the restore again, or pass --force"
    fi
    admin_sql "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $(sql_literal "$POSTGRES_DB")" \
      || abort_swap "could not end the connections to ${POSTGRES_DB} (only a superuser can end a superuser's session)"
    # Ended sessions take a moment to go, and the rename needs them gone.
    tries=0
    until rename_db "$POSTGRES_DB" "$previous_db" 2>/dev/null; do
      tries=$((tries + 1))
      [ "$tries" -lt 10 ] || abort_swap "could not set ${POSTGRES_DB} aside to replace it"
      sleep 1
    done
  fi
  if ! rename_db "$scratch_db" "$POSTGRES_DB"; then
    if [ "$live_exists" -gt 0 ] && rename_db "$previous_db" "$POSTGRES_DB"; then
      set_connections "$POSTGRES_DB" true || warn "could not reopen ${POSTGRES_DB} to connections; run: ${reopen_hint}"
      discard_scratch
      die "could not put the restored database in place; ${POSTGRES_DB} was left as it was"
    fi
    die "could not put the restored database in place. No data was lost: the previous database is now named ${previous_db} and the restored one ${scratch_db}. Rename the one you want with: ALTER DATABASE \"<name>\" RENAME TO \"${POSTGRES_DB}\"; ${reopen_hint}"
  fi
  # shellcheck disable=SC2016
  on_exit 'rm -rf "${WORK_DIR}"'
  if [ "$live_exists" -gt 0 ]; then
    dropdb --maintenance-db="$maint_db" --if-exists --force "$previous_db" \
      || warn "the restore succeeded, but the previous database could not be removed; drop ${previous_db} when convenient"
  fi

  if [ "$database_only" = true ]; then
    log "File storage left untouched (--database-only)"
  elif [ -f "${dir}/storage.tar.gz" ]; then
    log "Restoring file storage..."
    find "$STORAGE_DIR" -mindepth 1 -maxdepth 1 -exec rm -rf {} +
    tar -C "$STORAGE_DIR" --numeric-owner -xzpf "${dir}/storage.tar.gz"
  else
    warn "backup has no storage.tar.gz; file storage left untouched"
  fi

  if [ -f "${dir}/config/.env" ] && [ -f "${CONFIG_DIR}/.env" ] \
    && [ "$(env_secret_hash "${dir}/config/.env")" != "$(env_secret_hash "${CONFIG_DIR}/.env")" ]; then
    warn "SECRET_KEY_BASE in this backup differs from the current .env."
    warn "Encrypted data will not decrypt until you use the backup's value (see ${dir#"${BACKUP_DIR}"/}/config/.env)."
  fi

  if [ "${SURE_RECOVER:-}" = 1 ]; then
    # Called by `recover`, which pins the image and starts the app itself.
    log "Restored Sure ${version}."
    return 0
  fi
  log "Restored Sure ${version}. Next, on the host:"
  log "  1. Run the app on ${image}${image_by_commit:+ (or ${image_by_commit} for non-release builds)}:"
  if [ -f "${CONFIG_DIR}/compose.restore.yml" ]; then
    log "     set the web and worker image in compose.restore.yml (it overrides SURE_IMAGE_TAG)"
  else
    log "     set SURE_IMAGE_TAG=${version} in .env, or the web/worker image in your compose file"
  fi
  log "  2. docker compose up -d"
}

# --- recover (runs on the host) -----------------------------------------------

# ask PROMPT DEFAULT: prints the answer, or DEFAULT on an empty line or EOF.
ask() {
  if [ "$assume_yes" = true ]; then
    printf '%s\n' "$2"
    return 0
  fi
  printf '%s%s: ' "$1" "${2:+ [$2]}" >&2
  answer=""
  read -r answer || true
  printf '%s\n' "${answer:-$2}"
}

env_set() {
  awk -v k="$2" -v v="$3" '
    $0 ~ "^" k "=" { if (!done) print k "=" v; done = 1; next }
    { print }
    END { if (!done) print k "=" v }
  ' "$1" > "$1.tmp"
  mv "$1.tmp" "$1"
  chmod 0600 "$1"
}

env_get() {
  sed -n "s/^$2=//p" "$1" 2>/dev/null | tail -n 1 | sed -e 's/[[:space:]]*#.*$//' -e 's/^"\(.*\)"$/\1/'
}

port_in_use() {
  docker ps --format '{{.Ports}}' 2>/dev/null | grep -q ":$1->" && return 0
  if command -v nc >/dev/null 2>&1 && nc -z 127.0.0.1 "$1" >/dev/null 2>&1; then
    return 0
  fi
  return 1
}

# Compose projects with a running Sure web or worker container.
running_sure_projects() {
  docker ps --format '{{.Label "com.docker.compose.project"}}|{{.Label "com.docker.compose.service"}}|{{.Image}}' 2>/dev/null \
    | awk -F'|' '($2 == "web" || $2 == "worker") && $3 ~ /sure/ { print ($1 == "" ? "(not compose)" : $1) }' \
    | sort -u
}

cmd_recover() {
  bundle=""
  target=""
  port=""
  worker=""
  assume_yes=false
  start=true
  while [ $# -gt 0 ]; do
    case "$1" in
      --target) target=$2; shift 2 ;;
      --port) port=$2; shift 2 ;;
      --with-worker) worker=yes; shift ;;
      --without-worker) worker=no; shift ;;
      --yes) assume_yes=true; shift ;;
      --no-start) start=false; shift ;;
      -h | --help) usage; return 0 ;;
      -*) die "unknown option for recover: $1" ;;
      *) bundle=$1; shift ;;
    esac
  done

  [ -n "$bundle" ] && [ -f "${bundle}/manifest.json" ] || die "recover needs a backup bundle folder (one with manifest.json)"
  bundle=$(cd "$bundle" && pwd)
  if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
    die "Docker with the Compose plugin is required (https://docs.docker.com/compose/install/)"
  fi

  version=$(manifest_value "$bundle" sure_version)
  image=$(manifest_value "$bundle" image)
  created=$(manifest_value "$bundle" created_at)
  [ -n "$version" ] && [ -n "$image" ] || die "cannot read version and image from ${bundle}/manifest.json"
  [ -f "${bundle}/config/.env" ] || die "the bundle has no config/.env; restore it by hand (see docs/hosting/docker.md)"
  compose_file=""
  for f in compose.yml compose.yaml docker-compose.yml docker-compose.yaml; do
    [ -f "${bundle}/config/${f}" ] && { compose_file=$f; break; }
  done
  [ -n "$compose_file" ] || die "the bundle has no compose file; restore it by hand (see docs/hosting/docker.md)"

  log "Backup: Sure ${version}, taken ${created:-at an unknown time} (${image})"
  log "Verifying checksums..."
  if command -v sha256sum >/dev/null 2>&1; then
    (cd "$bundle" && sha256sum -c SHA256SUMS >/dev/null) || die "checksum verification failed"
  elif command -v shasum >/dev/null 2>&1; then
    (cd "$bundle" && shasum -a 256 -c SHA256SUMS >/dev/null) || die "checksum verification failed"
  else
    warn "no sha256sum or shasum; skipping checksum verification here (restore checks it again)"
  fi

  # Where to put the restored project. Its folder name becomes the Compose
  # project name, which names its containers and data volumes.
  [ -n "$target" ] || target=$(ask "Folder for the restored instance" "$(pwd)/sure-restore-${version}")
  # A literal "~" typed at the prompt is not expanded by the shell.
  # shellcheck disable=SC2088
  case "$target" in
    "~") target=$HOME ;;
    "~/"*) target="${HOME}/${target#"~/"}" ;;
  esac
  if [ -e "$target" ] && [ -n "$(ls -A "$target" 2>/dev/null)" ]; then
    die "${target} is not empty. Pick a new folder; to roll back an existing install, use 'restore' there instead."
  fi
  created_target=false
  [ -d "$target" ] || created_target=true
  mkdir -p "$target"
  target=$(cd "$target" && pwd)
  # On abort, remove the folder only if this run created it.
  cleanup_target() { [ "$created_target" = true ] && rmdir "$target" 2>/dev/null; true; }

  project=$(basename "$target" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9_-' | sed 's/^[^a-z0-9]*//')
  [ -n "$project" ] || project="sure-restore"
  if [ -n "$(docker ps -aq --filter "label=com.docker.compose.project=${project}")" ] \
    || [ -n "$(docker volume ls -q --filter "label=com.docker.compose.project=${project}")" ]; then
    cleanup_target
    die "Docker already has containers or volumes for a project named '${project}'. Pick a folder with another name, or this would overwrite that instance's data."
  fi

  # Other Sure instances on this machine.
  others=$(running_sure_projects)
  if [ -n "$others" ]; then
    warn "Other Sure instances are running on this machine: $(echo "$others" | tr '\n' ' ')"
    cat >&2 <<'EOF'
If one of them holds the same data as this backup, running both at once means:
  - Both workers sync the same bank connections. Some providers rotate access
    tokens on every sync, so the copy can disconnect the original.
  - Scheduled jobs, such as recurring transactions and emails, run twice.
  - Signing in to both on the same host name (e.g. localhost on another port)
    signs you out of the other, because browsers share cookies across ports.
Starting the restored instance without its worker avoids the first two.
EOF
    [ -n "$worker" ] || case "$(ask "Start the restored worker too? (no = web only, abort = stop here)" "no")" in
      y | yes) worker=yes ;;
      abort | a | q) cleanup_target; die "aborted" ;;
      *) worker=no ;;
    esac
  fi
  [ -n "$worker" ] || worker=yes

  backup_port=$(env_get "${bundle}/config/.env" PORT)
  backup_port=${backup_port:-3000}
  if [ -z "$port" ]; then
    port=$backup_port
    if port_in_use "$port"; then
      suggestion=$port
      while port_in_use "$suggestion"; do suggestion=$((suggestion + 1)); done
      warn "port ${port} is already in use"
      port=$(ask "Port for the restored instance" "$suggestion")
    fi
  fi
  case "$port" in "" | *[!0-9]*) die "invalid port: ${port}" ;; esac
  port_in_use "$port" && warn "port ${port} looks busy; the web container may fail to start"

  log "Restoring into ${target} (project '${project}', port ${port})"
  cp -R "${bundle}/config/." "${target}/"
  # Use this copy of the script, which may be newer than the bundle's.
  mkdir -p "${target}/bin"
  cp "$0" "${target}/bin/sure-backup"
  chmod 0755 "${target}/bin/sure-backup"
  mkdir -p "${target}/backups/${version}"
  cp -R "$bundle" "${target}/backups/${version}/"
  name=$(basename "$bundle")

  compose_files=$compose_file
  for f in compose.override.yml compose.override.yaml docker-compose.override.yml docker-compose.override.yaml; do
    [ -f "${target}/${f}" ] && compose_files="${compose_files}:${f}"
  done
  compose_files="${compose_files}:compose.restore.yml"

  cat > "${target}/compose.restore.yml" <<EOF
# Written by \`sure-backup recover\` from backup ${version}/${name}.
# Pins web and worker to the backed-up version and adds the sure-backup
# service; COMPOSE_FILE in .env loads it with the main compose file.
# To upgrade later, change the image here (or remove it to follow the
# compose file's tag) and run: docker compose pull && docker compose up -d
services:
  web:
    image: ${image}
  worker:
    image: ${image}
  sure-backup:
    profiles: [sure-backup]
    image: ${image}
    user: "0"
    entrypoint: ["/usr/local/bin/sure-backup"]
    volumes:
      - ./bin/sure-backup:/usr/local/bin/sure-backup:ro
      - ./backups:/backups
      - app-storage:/rails/storage
      - .:/config:ro
    environment:
      POSTGRES_HOST: db
      POSTGRES_USER: \${POSTGRES_USER:-sure_user}
      POSTGRES_PASSWORD: \${POSTGRES_PASSWORD:-sure_password}
      POSTGRES_DB: \${POSTGRES_DB:-sure_production}
    depends_on:
      db:
        condition: service_healthy
    networks:
      - sure_net
EOF
  env_set "${target}/.env" COMPOSE_PROJECT_NAME "$project"
  env_set "${target}/.env" COMPOSE_FILE "$compose_files"
  env_set "${target}/.env" PORT "$port"

  # Values exported in the caller's shell override .env, and could point
  # Compose at the original install. Pin every call below to this project.
  export COMPOSE_PROJECT_NAME="$project" COMPOSE_FILE="$compose_files"
  unset COMPOSE_PROFILES COMPOSE_PROJECT_DIR
  cd "$target"
  restore_cmd="docker compose run --rm -e SURE_RECOVER=1 sure-backup restore ${version}/${name} --yes"

  # The copied compose files must not reach shared storage: external volumes
  # or networks, or host paths outside this folder, could belong to the
  # original install, whose database or files the restore would replace.
  resolved=$(docker compose config 2>/dev/null) || die "docker compose cannot read the copied configuration in ${target}"
  shared=$(printf '%s\n' "$resolved" | awk -v t="$target" '
    /^[[:space:]]*external: true/ { print "  an external volume or network (external: true)" }
    /^[[:space:]]*source: \// { if (index($2, t) != 1) print "  host path " $2 }
  ' | sort -u)
  if [ -n "$shared" ]; then
    warn "the copied compose configuration uses storage outside ${target}:"
    printf '%s\n' "$shared" >&2
    die "restoring here could overwrite another instance's data. Make these local to ${target} in its compose files, then run there: docker compose up -d db redis && ${restore_cmd}"
  fi

  # Local files the compose files mount (e.g. "- ./certs/ca.pem:/...") are not
  # part of the backup. Docker would create empty directories in their place
  # and the containers using them would fail to start.
  missing_mounts=""
  for f in $(echo "$compose_files" | tr ':' ' '); do
    # The pattern stops at whitespace, so word splitting is safe here.
    # shellcheck disable=SC2013
    for src in $(sed -n 's/^[[:space:]]*-[[:space:]]*\(\.\/[^:[:space:]]*\):.*/\1/p' "${target}/${f}"); do
      case "$src" in ./backups | ./backups/* | ./bin/sure-backup) continue ;; esac
      [ -e "${target}/${src}" ] || missing_mounts="${missing_mounts} ${src}"
    done
  done
  if [ -n "$missing_mounts" ]; then
    warn "the compose files mount local paths that are not in the backup:${missing_mounts}"
    warn "copy them into ${target} from the original install before starting."
    start=false
  fi

  if [ "$start" != true ]; then
    log "Prepared ${target}. Start it with:"
    services="web worker"; [ "$worker" = yes ] || services="web"
    log "  cd ${target}"
    log "  export COMPOSE_PROJECT_NAME=${project} COMPOSE_FILE=${compose_files}"
    log "  docker compose up -d db redis && ${restore_cmd} && docker compose up -d ${services}"
    return 0
  fi

  log "Starting the database..."
  docker compose up -d db redis
  log "Restoring the backup..."
  docker compose run --rm -e SURE_RECOVER=1 sure-backup restore "${version}/${name}" --yes
  if [ "$worker" = yes ]; then
    log "Starting web and worker..."
    docker compose up -d web worker
  else
    log "Starting web only (no worker)..."
    docker compose up -d web
  fi

  url="http://localhost:${port}"
  if command -v curl >/dev/null 2>&1; then
    log "Waiting for ${url} ..."
    tries=0
    until curl -fsS -o /dev/null "${url}/up" 2>/dev/null; do
      tries=$((tries + 1))
      [ "$tries" -lt 60 ] || { warn "the app did not answer within 3 minutes; check: docker compose logs web"; break; }
      sleep 3
    done
  fi

  log ""
  log "Restored Sure ${version} is running at ${url}"
  log "  Folder:  ${target}"
  log "  Manage:  cd ${target} && docker compose ps | logs web | down"
  [ "$worker" = yes ] || log "  Worker:  not started; start it with 'docker compose up -d worker' once the original instance is stopped"
  log "  Remove:  cd ${target} && docker compose down -v   (deletes this copy's data)"
}

# --- prune / offsite ----------------------------------------------------------

cmd_prune() {
  check_keep_days
  minutes=$((BACKUP_KEEP_DAYS * 1440))
  log "Pruning scheduled backups older than ${BACKUP_KEEP_DAYS} days (manual backups are kept)..."
  find "$BACKUP_DIR" -mindepth 2 -maxdepth 2 -type d -name '*-scheduled' -mmin "+${minutes}" ! -path '*/.tmp-*' \
    | while read -r d; do
        log "  removing ${d#"${BACKUP_DIR}"/}"
        rm -rf "$d"
      done
  # Version directories left empty by pruning.
  find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d ! -name '.tmp-*' -empty -exec rmdir {} + 2>/dev/null || true
  # Interrupted runs.
  find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d -name '.tmp-*' -mmin +1440 -exec rm -rf {} + 2>/dev/null || true
}

cmd_scheduled() {
  check_keep_days
  cmd_create --scheduled
  cmd_prune
}

# Seconds until the next daily run at H:M (UTC).
seconds_until() {
  now=$(date -u +%s)
  next=$(date -u -d "$(date -u +%Y-%m-%d) $1:$2:00" +%s)
  [ "$next" -gt "$now" ] || next=$((next + 86400))
  echo $((next - now))
}

cmd_daemon() {
  check_db_env
  check_keep_days
  ensure_deps

  # Only daily schedules: "M H * * *" with a numeric minute and hour.
  set -f
  # shellcheck disable=SC2086
  set -- $BACKUP_SCHEDULE
  set +f
  minute=${1:-}; hour=${2:-}
  if [ $# -ne 5 ] || [ "$3" != "*" ] || [ "$4" != "*" ] || [ "$5" != "*" ] \
    || ! [ "$minute" -ge 0 ] 2>/dev/null || [ "$minute" -gt 59 ] \
    || ! [ "$hour" -ge 0 ] 2>/dev/null || [ "$hour" -gt 23 ]; then
    die "BACKUP_SCHEDULE must be a daily time like \"0 2 * * *\" (minute hour * * *, UTC); got \"${BACKUP_SCHEDULE}\""
  fi
  minute=$((minute + 0)); hour=$((hour + 0))
  hhmm=$(printf '%02d:%02d' "$hour" "$minute")

  if [ -n "${BACKUP_DESTINATION:-}" ]; then
    warn "BACKUP_DESTINATION is ignored here; off-site copies are made by the backup-offsite service"
  fi
  # Exit promptly on docker stop; the sleep runs in the background so the trap fires.
  trap 'exit 0' TERM INT
  log "Scheduled backups every day at ${hhmm} UTC into ${BACKUP_DIR}"
  while true; do
    wait_s=$(seconds_until "$hour" "$minute")
    log "Next backup in $((wait_s / 3600))h $((wait_s % 3600 / 60))m"
    sleep "$wait_s" &
    wait $!
    # Run the scheduled backup with set -e and capture its exit status, so a
    # failed step stops the run before it reports "Done" or prunes old backups.
    set +e
    ( set -e; cmd_scheduled )
    status=$?
    set -e
    [ "$status" -eq 0 ] || warn "scheduled backup failed; retrying at the next scheduled time"
  done
}

# --- host mode -----------------------------------------------------------------
#
# Run on the host from the folder with compose.yml, `create`, `restore`,
# `prune` and `scheduled` start this script once in a container from the
# exact image of the install's `web` container, with its uploaded-files
# volume, network and database settings. No backup service needed, so it
# also works for Sure 0.7.5 and older.

on_host() {
  [ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ] && command -v docker >/dev/null 2>&1
}

host_run() {
  docker compose version >/dev/null 2>&1 || die "Docker with the Compose plugin is required"
  cid=$(docker compose ps -aq web 2>/dev/null | head -n 1)
  [ -n "$cid" ] || die "no Sure 'web' container for the Compose project in $(pwd). Run this from the folder with your compose.yml; the app must have been started at least once."

  # An idle app holds no database connections, so the in-container check can
  # miss it; here Docker can tell whether the app is running.
  if [ "$1" = restore ]; then
    case " $* " in *" --force "*) ;; *)
      if [ -n "$(docker compose ps -q --status running web worker 2>/dev/null)" ]; then
        die "the app is running. Stop it first: docker compose stop web worker (or pass --force)"
      fi
    esac
  fi

  inspect() { docker inspect -f "$1" "$cid"; }
  image=${SURE_HOST_IMAGE:-$(inspect '{{.Image}}')}
  workdir=$(inspect '{{index .Config.Labels "com.docker.compose.project.working_dir"}}')
  workdir=${workdir:-$(pwd)}
  # A Go template for docker inspect, not shell expansion.
  # shellcheck disable=SC2016
  network=$(inspect '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}}{{"\n"}}{{end}}' | sed -n '1p')
  network=${SURE_HOST_NETWORK:-$network}
  storage=$(inspect '{{range .Mounts}}{{if eq .Destination "/rails/storage"}}{{if eq .Type "volume"}}{{.Name}}{{else}}{{.Source}}{{end}}{{end}}{{end}}')
  container_env=$(inspect '{{range .Config.Env}}{{println .}}{{end}}')
  env_of() { printf '%s\n' "$container_env" | sed -n "s/^$1=//p" | tail -n 1; }

  backups=$(env_get "${workdir}/.env" BACKUP_DIR)
  backups=${backups:-./backups}
  case "$backups" in /*) ;; *) backups="${workdir}/${backups#./}" ;; esac
  mkdir -p "$backups"
  script_path=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")

  # Database credentials go through a private env file, not the command line.
  host_tmp=$(umask 077 && mktemp -d)
  # During upgrade-postgres, its cleanup (which also removes host_tmp) stays in place.
  if [ -n "${upgrading:-}" ]; then
    on_exit upgrade_cleanup
  else
    # shellcheck disable=SC2016
    on_exit 'rm -rf "${host_tmp}"'
  fi
  {
    echo "POSTGRES_HOST=${SURE_HOST_DB:-$(env_of DB_HOST)}"
    [ -z "${SURE_RECOVER:-}" ] || echo "SURE_RECOVER=${SURE_RECOVER}"
    echo "POSTGRES_PORT=${SURE_HOST_PORT:-$(env_of DB_PORT)}"
    echo "POSTGRES_USER=$(env_of POSTGRES_USER)"
    echo "POSTGRES_PASSWORD=$(env_of POSTGRES_PASSWORD)"
    echo "POSTGRES_DB=$(env_of POSTGRES_DB)"
    echo "BUILD_COMMIT_SHA=$(env_of BUILD_COMMIT_SHA)"
    for v in BACKUP_KEEP_DAYS INSTANCE_ID; do
      val=$(env_get "${workdir}/.env" "$v")
      [ -z "$val" ] || echo "${v}=${val}"
    done
  } > "${host_tmp}/env"

  # Build `docker run [options] IMAGE SUBCOMMAND ARGS` by prepending to "$@".
  set -- "$image" "$@"
  set -- --entrypoint /usr/local/bin/sure-backup "$@"
  set -- -v "${script_path}:/usr/local/bin/sure-backup:ro" "$@"
  set -- -v "${workdir}:/config:ro" -v "${backups}:/backups" "$@"
  if [ -n "$storage" ]; then
    set -- -v "${storage}:/rails/storage" "$@"
  else
    warn "the web container has no /rails/storage mount; uploaded files are not included"
  fi
  [ -n "$network" ] && set -- --network "$network" "$@"
  [ -t 0 ] && set -- -t "$@"
  # create writes the bundle it made here, read back into host_result.
  mkdir "${host_tmp}/result"
  set -- -v "${host_tmp}/result:/sure-result" -e SURE_RESULT_FILE=/sure-result/bundle "$@"
  set -- --rm -i --user 0 --env-file "${host_tmp}/env" "$@"

  host_status=0
  docker run "$@" || host_status=$?
  host_result=$(cat "${host_tmp}/result/bundle" 2>/dev/null || true)
  rm -rf "$host_tmp"
  return "$host_status"
}

# --- upgrade-postgres (runs on the host) ---------------------------------------
#
# Moves the Sure database to the PostgreSQL major version the compose file now
# points at, by backup and restore: take a forced backup from the old server,
# set the old data aside inside the volume, start the new server and restore.
# Only Sure's database is carried over, so the server must be used for nothing
# else.

upgrade_cleanup() {
  cleanup_status=$?
  [ -z "${old_server:-}" ] || docker stop "$old_server" >/dev/null 2>&1 || true
  [ -z "${upgrade_net:-}" ] || docker network rm "$upgrade_net" >/dev/null 2>&1 || true
  [ -z "${host_tmp:-}" ] || rm -rf "$host_tmp"
  # Failures print their own instructions; an interruption (exit 130 from
  # on_exit) prints them for the step it stopped in.
  [ "$cleanup_status" -eq 130 ] || return 0
  echo "[sure-backup] Interrupted." >&2
  case "${upgrade_phase:-}" in
    stopped) stopped_help ;;
    moving) upgrade_rollback_help ;;
    restored) warn "the database is now on PostgreSQL ${target_major}. Start Sure with: docker compose up -d" ;;
    *) echo "[sure-backup] Nothing was changed." >&2 ;;
  esac
}

# Written into the volume before the old data is moved and removed once the
# restore has succeeded. While it is there, the upgrade has not finished: it
# holds the command that puts the old data back, and db-version-check refuses
# to start the database.
UPGRADE_MARKER=.sure-upgrade-incomplete

# How the old server was configured, for the instructions below.
old_config_hint() {
  hint="the db volume mount back to ${old_mount}"
  [ "$old_pgdata" = /var/lib/postgresql/data ] || hint="${hint}, with PGDATA=${old_pgdata}"
  printf '%s' "$hint"
}

upgrade_rollback_help() {
  cat >&2 <<EOF
[sure-backup] Your PostgreSQL ${old_major} data is intact in the volume ${volume}, set aside in ${aside}/
[sure-backup] (or still in its place, if it had not been moved yet).
[sure-backup] To go back to PostgreSQL ${old_major}:
[sure-backup]   1. docker compose stop
[sure-backup]   2. docker run --rm -v ${volume}:/v alpine sh -c '${putback_cmd}'
[sure-backup]   3. In your compose file, set the PostgreSQL image (x-db-image in compose.example.yml)
[sure-backup]      back to version ${old_major} AND $(old_config_hint)
[sure-backup]      (both, or the server starts empty).
[sure-backup]   4. docker compose up -d
[sure-backup] Or, after step 2, fix the problem above and run upgrade-postgres again.
[sure-backup] The backup taken before the upgrade is ${bundle_id:-in your backups folder}.
EOF
}

# For failures after Sure was stopped but before the old data was touched.
die_stopped() {
  echo "[sure-backup] ERROR: $*" >&2
  stopped_help
  exit 1
}

stopped_help() {
  cat >&2 <<EOF
[sure-backup] Your data was not changed, but Sure is stopped. Fix the problem above and run this
[sure-backup] again, or to keep using PostgreSQL ${old_major} for now, set the PostgreSQL image in your
[sure-backup] compose file back to version ${old_major} AND $(old_config_hint), then: docker compose up -d
EOF
}

cmd_upgrade_postgres() {
  assume_yes=false
  old_image=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --yes) assume_yes=true; shift ;;
      --old-image) old_image=$2; shift 2 ;;
      -h | --help) usage; return 0 ;;
      *) die "unknown option for upgrade-postgres: $1" ;;
    esac
  done

  on_host || die "upgrade-postgres runs on the host, from the folder with your compose file: sh sure-backup upgrade-postgres"
  docker compose version >/dev/null 2>&1 || die "Docker with the Compose plugin is required"
  resolved=$(docker compose config 2>/dev/null) || die "docker compose cannot read the configuration in $(pwd)"

  # What the compose file asks for: the db image and the volume holding its data.
  target_image=$(printf '%s\n' "$resolved" | awk '
    /^  db:$/ { f = 1; next } /^  [^ ]/ { f = 0 }
    f && $1 == "image:" { print $2; exit }')
  volume_key=$(printf '%s\n' "$resolved" | awk '
    /^  db:$/ { f = 1; next } /^  [^ ]/ { f = 0 }
    f && $1 == "source:" { src = $2 }
    f && $1 == "target:" && $2 ~ /^\/var\/lib\/postgresql/ { print src; exit }')
  volume=$(printf '%s\n' "$resolved" | awk -v k="$volume_key" '
    /^volumes:$/ { v = 1; next } /^[^ ]/ { v = 0 }
    v && $0 == "  " k ":" { hit = 1; next }
    v && /^  [^ ]/ { hit = 0 }
    v && hit && $1 == "name:" { print $2; exit }')
  tool_image=$(printf '%s\n' "$resolved" | awk '
    /^  web:$/ { f = 1; next } /^  [^ ]/ { f = 0 }
    f && $1 == "image:" { print $2; exit }')
  if [ -z "$target_image" ] || [ -z "$volume" ] || [ -z "$tool_image" ]; then
    die "cannot find the 'db' service's image and data volume, and the 'web' image, in the compose configuration. This command needs the service names from compose.example.yml."
  fi
  docker volume inspect "$volume" >/dev/null 2>&1 || die "the volume ${volume} does not exist yet, so there is nothing to upgrade. Start Sure with: docker compose up -d"

  cid=$(docker compose ps -aq web 2>/dev/null | head -n 1)
  [ -n "$cid" ] || die "no Sure 'web' container for the Compose project in $(pwd); the app must have been started at least once"
  container_env=$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$cid")
  env_of() { printf '%s\n' "$container_env" | sed -n "s/^$1=//p" | tail -n 1; }
  db_user=$(env_of POSTGRES_USER)
  db_name=$(env_of POSTGRES_DB)
  # The backup comes from this project's db volume and the restore must land
  # there too, never on a server the app reaches some other way.
  db_host=$(env_of DB_HOST)
  if [ "$db_host" != db ]; then
    die "the app connects to the database at '${db_host:-unknown}', not the 'db' service, and upgrade-postgres only upgrades the 'db' service's own data. Nothing was changed."
  fi
  project=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "$cid")
  running_image=$(docker inspect -f '{{.Image}}' "$cid")

  major_of() { sed -n 's/.* \([0-9][0-9]*\)\..*/\1/p'; }
  log "Checking ${target_image}..."
  target_major=$(docker run --rm --entrypoint postgres "$target_image" --version | major_of)
  case "$target_major" in "" | *[!0-9]*) die "cannot read the PostgreSQL version of ${target_image}" ;; esac

  # What the volume holds. Up to 17 the data sits at the volume root, or in
  # data/ under it with a custom PGDATA; from 18 the image keeps it in
  # <major>/docker.
  # vol_sh SCRIPT [ARG...]: runs SCRIPT in a container with the volume at /v.
  vol_sh() {
    vol_script=$1
    shift
    docker run --rm --user 0 --entrypoint sh -v "${volume}:/v" "$running_image" -c "$vol_script" sh "$@"
  }
  # The scripts below run inside that container, so their $ is not ours.
  # shellcheck disable=SC2016
  state=$(vol_sh '
    if [ -f /v/PG_VERSION ]; then echo "root $(cat /v/PG_VERSION) -"
    elif [ -f /v/data/PG_VERSION ]; then echo "data $(cat /v/data/PG_VERSION) -"
    else
      found="none - -"
      for f in /v/[0-9]*/docker/PG_VERSION; do
        [ -f "$f" ] || continue
        m=$(cat "$f")
        [ "$m" = "$1" ] && continue
        d=${f#/v/}
        if [ "$found" = "none - -" ]; then found="versioned $m ${d%%/*}"; else found="several - -"; fi
      done
      echo "$found"
    fi
    [ -f "/v/$1/docker/PG_VERSION" ] && echo has_target || echo no_target
    for a in /v/pg*-old; do [ -e "$a" ] && printf "%s " "${a#/v/}"; done; echo
    [ -f "/v/$2" ] && cat "/v/$2"; true' "$target_major" "$UPGRADE_MARKER")
  layout=$(printf '%s\n' "$state" | sed -n '1p' | cut -d' ' -f1)
  old_major=$(printf '%s\n' "$state" | sed -n '1p' | cut -d' ' -f2)
  old_dir=$(printf '%s\n' "$state" | sed -n '1p' | cut -d' ' -f3)
  has_target=$(printf '%s\n' "$state" | sed -n '2p')
  asides=$(printf '%s\n' "$state" | sed -n '3p')
  marker_value() { printf '%s\n' "$state" | sed -n '4,$p' | sed -n "s/^$1=//p" | head -n 1; }

  # An earlier run stopped part-way: put its data back before anything else.
  if [ -n "$(marker_value putback)" ]; then
    die "an earlier upgrade-postgres run did not finish. Your PostgreSQL $(marker_value major) data is in the volume ${volume}, some or all of it set aside in pg$(marker_value major)-old/. Nothing was changed. Put it back with:
  docker compose stop
  docker run --rm -v ${volume}:/v alpine sh -c '$(marker_value putback)'
then fix what made the earlier run fail and run upgrade-postgres again, or, to stay on PostgreSQL $(marker_value major), set the PostgreSQL image back to that version AND $(marker_value config)."
  fi

  case "$layout" in
    none)
      if [ "$has_target" = has_target ]; then
        log "The database is already on PostgreSQL ${target_major}; nothing to do."
      else
        log "No PostgreSQL data found in ${volume}; nothing to upgrade."
      fi
      return 0
      ;;
    several) die "${volume} holds data from several PostgreSQL versions in <major>/docker folders. Decide which one to keep before upgrading; see docs/hosting/docker.md." ;;
  esac
  case "$old_major" in "" | *[!0-9]*) die "cannot read the PostgreSQL version of the data in ${volume}" ;; esac
  if [ "$old_major" -ge "$target_major" ]; then
    die "the data in ${volume} is PostgreSQL ${old_major} and the compose file asks for ${target_major}; this command only upgrades to a newer major version"
  fi
  if [ "$has_target" = has_target ]; then
    die "${volume} holds PostgreSQL ${old_major} data and also a PostgreSQL ${target_major} database. Decide which one to keep before upgrading; see docs/hosting/docker.md."
  fi
  aside="pg${old_major}-old"
  case " ${asides}" in
    *" ${aside} "*) die "${volume} already has a ${aside} folder, from an earlier upgrade, where this one would set the PostgreSQL ${old_major} data aside. Nothing was changed. Check what it holds, then remove or rename it: docker run --rm -v ${volume}:/v alpine ls -la /v/${aside}" ;;
  esac

  # How the old server was set up (for the instructions), where its data is
  # in the volume, how to move it aside, and how to put it back.
  # move_script runs in the volume container, so its $ is not ours.
  # shellcheck disable=SC2016
  case "$layout" in
    root)
      old_mount=/var/lib/postgresql/data
      old_pgdata=$old_mount
      old_rel=""
      # The marker stays where it is; everything else moves.
      move_script='mkdir "/v/$1"
        for f in /v/* /v/.[!.]*; do
          [ -e "$f" ] || continue
          [ "$f" = "/v/$1" ] || [ "$f" = "/v/$2" ] || mv "$f" "/v/$1/"
        done'
      putback_layout="if [ -d /v/${aside} ]; then mv /v/${aside}/* /v/${aside}/.[!.]* /v/ 2>/dev/null; rmdir /v/${aside}; fi"
      old_check=/v/PG_VERSION
      ;;
    data)
      old_mount=/var/lib/postgresql/data
      old_pgdata=${old_mount}/data
      old_rel=/data
      move_script='mv /v/data "/v/$1"'
      putback_layout="if [ -d /v/${aside} ]; then [ ! -e /v/data ] && mv /v/${aside} /v/data; fi"
      old_check=/v/data/PG_VERSION
      ;;
    versioned)
      old_mount=/var/lib/postgresql
      old_pgdata=${old_mount}/${old_dir}/docker
      old_rel=/${old_dir}/docker
      # Not as pg16-old/docker: PostgreSQL 18 refuses to start beside any
      # other */docker cluster.
      move_script='mv "/v/$3/docker" "/v/$1"; rmdir "/v/$3" 2>/dev/null || true'
      putback_layout="if [ -d /v/${aside} ]; then [ ! -e /v/${old_dir}/docker ] && mkdir -p /v/${old_dir} && mv /v/${aside} /v/${old_dir}/docker; fi"
      old_check=/v/${old_dir}/docker/PG_VERSION
      ;;
    *) die "cannot tell how the data in ${volume} is laid out" ;;
  esac
  # Works whether the data was moved, partly moved or not moved yet; stops
  # (keeping the marker) if the old data is not back in its place.
  putback_cmd="rm -rf /v/${target_major} && { ${putback_layout}; } && [ -f ${old_check} ] && rm -f /v/${UPGRADE_MARKER}"

  # The restore needs tools at least as new as the new server. Prefer the
  # image the app runs on; fall back to the one the compose file asks for.
  running_tool_major=$(docker run --rm --entrypoint pg_dump "$running_image" --version 2>/dev/null | major_of)
  if [ "${running_tool_major:-0}" -ge "$target_major" ]; then
    tool_image=$running_image
  else
    log "Checking ${tool_image}..."
    tool_major=$(docker run --rm --entrypoint pg_dump "$tool_image" --version 2>/dev/null | major_of)
    if [ "${tool_major:-0}" -lt "$target_major" ]; then
      die "PostgreSQL ${target_major} needs a Sure version that ships its client tools, but ${tool_image} has version ${tool_major:-none}. Set SURE_IMAGE_TAG to a newer Sure release first."
    fi
  fi
  # The backup is taken with the app's own image, so the bundle's restore.sh,
  # which runs the image recorded in the bundle, can read it: an older
  # pg_restore cannot read a dump made by a newer pg_dump.
  if [ "${running_tool_major:-0}" -lt "$old_major" ]; then
    die "the Sure image the app runs on ships pg_dump ${running_tool_major:-none}, which cannot back up PostgreSQL ${old_major}. Start a newer Sure release on PostgreSQL ${old_major} first (only SURE_IMAGE_TAG changed), then upgrade. Nothing was changed."
  fi
  backup_image=$running_image

  # The old server image, to read the old data one last time.
  if [ -z "$old_image" ]; then
    db_cid=$(docker compose ps -aq db 2>/dev/null | head -n 1)
    [ -z "$db_cid" ] || old_image=$(docker inspect -f '{{.Config.Image}}' "$db_cid")
    if [ -z "$old_image" ] || [ "$old_image" = "$target_image" ]; then
      case "$target_image" in
        pgvector/pgvector:pg"${target_major}"*) old_image="pgvector/pgvector:pg${old_major}${target_image#pgvector/pgvector:pg"${target_major}"}" ;;
        postgres:"${target_major}"*) old_image="postgres:${old_major}" ;;
        *) die "cannot tell which image ran PostgreSQL ${old_major}; pass it with --old-image, e.g. --old-image postgres:${old_major}" ;;
      esac
    fi
  fi

  # Databases besides Sure's that hold data, including the maintenance
  # database "postgres" when someone has created anything in it.
  other_databases() {
    docker exec "$1" psql -X -q -t -A -U "$db_user" -d postgres \
      -c "SELECT datname FROM pg_database WHERE NOT datistemplate AND datname NOT IN ('postgres', '$(printf '%s' "$db_name" | sed "s/'/''/g")')" \
      || return 1
    [ "$db_name" != postgres ] || return 0
    user_ns="SELECT oid FROM pg_namespace WHERE nspname NOT IN ('pg_catalog', 'information_schema') AND nspname NOT LIKE 'pg\_toast%' AND nspname NOT LIKE 'pg\_temp%'"
    postgres_objects=$(docker exec "$1" psql -X -q -t -A -U "$db_user" -d postgres -c "SELECT
        (SELECT count(*) FROM pg_namespace WHERE oid IN (${user_ns}) AND nspname <> 'public')
      + (SELECT count(*) FROM pg_class WHERE relnamespace IN (${user_ns}))
      + (SELECT count(*) FROM pg_proc WHERE pronamespace IN (${user_ns}))
      + (SELECT count(*) FROM pg_type WHERE typnamespace IN (${user_ns}))
      + (SELECT count(*) FROM pg_largeobject_metadata)
      + (SELECT count(*) FROM pg_extension WHERE extname <> 'plpgsql')") \
      || return 1
    [ "$postgres_objects" = 0 ] || echo "postgres (it holds tables or other objects)"
  }
  # refuse_other_databases CONTAINER FAIL: FAIL is die or die_stopped.
  refuse_other_databases() {
    others=$(other_databases "$1") || "$2" "cannot list the databases on the PostgreSQL ${old_major} server"
    [ -z "$others" ] && return 0
    "$2" "this PostgreSQL server also holds other databases: $(echo "$others" | paste -sd ' ' -). Only ${db_name} would be carried over, so nothing was changed. Move them yourself (see docs/hosting/docker.md) or give Sure its own database server."
  }

  log "Upgrade ${db_name} from PostgreSQL ${old_major} to ${target_major} (${target_image}):"
  log "  1. stop Sure and take a backup"
  log "  2. set the PostgreSQL ${old_major} data aside in ${volume}/${aside} (kept until you delete it)"
  log "  3. start PostgreSQL ${target_major} and restore the backup"
  log "Sure is unavailable while this runs. Only the database ${db_name} is carried over:"
  log "other databases and extra roles on this server would be left behind. The command"
  log "stops if it finds other data, but that check is a backstop: you know your server."
  if [ "$assume_yes" != true ]; then
    [ -t 0 ] || die "refusing to upgrade without a TTY; pass --yes"
    printf 'Is this PostgreSQL server used only for Sure, and do you want to continue? Type "yes": '
    read -r answer
    [ "$answer" = "yes" ] || die "aborted; nothing was changed"
  fi

  db_cid=$(docker compose ps -q --status running db 2>/dev/null | head -n 1)
  [ -z "$db_cid" ] || refuse_other_databases "$db_cid" die

  upgrading=1
  on_exit upgrade_cleanup
  log "Stopping Sure..."
  upgrade_phase=stopped
  docker compose stop >/dev/null 2>&1

  log "Starting PostgreSQL ${old_major} (${old_image}) to take the backup..."
  upgrade_net="${project}_pg-upgrade"
  old_server="${project}-pg-upgrade-old"
  docker network create "$upgrade_net" >/dev/null
  # Mounted away from the paths the image declares as volumes (up to 17:
  # /var/lib/postgresql/data, from 18: /var/lib/postgresql). Mounted inside
  # one of them, Docker would add a mount point folder to our volume, and
  # PostgreSQL 18 refuses to start beside a stray data/ folder.
  # It is reached only on its own network, so it always listens on 5432,
  # whatever port the db service or the old postgresql.conf uses.
  docker run -d --rm --name "$old_server" --network "$upgrade_net" --network-alias pg-upgrade-old \
    -v "${volume}:/sure-pgdata" -e "PGDATA=/sure-pgdata${old_rel}" "$old_image" -p 5432 >/dev/null
  tries=0
  until docker exec "$old_server" pg_isready -q -U "$db_user" -d "$db_name" 2>/dev/null; do
    tries=$((tries + 1))
    if [ "$tries" -ge 60 ]; then
      docker logs --tail 20 "$old_server" >&2 2>&1 || true
      die_stopped "PostgreSQL ${old_major} did not start (its last log lines are above)."
    fi
    sleep 2
  done
  refuse_other_databases "$old_server" die_stopped

  backup_status=0
  SURE_HOST_IMAGE=$backup_image SURE_HOST_NETWORK=$upgrade_net SURE_HOST_DB=pg-upgrade-old SURE_HOST_PORT=5432 \
    host_run create --pre-upgrade || backup_status=$?
  [ "$backup_status" -eq 0 ] || die_stopped "the backup failed."
  # The bundle create reports, never one found by looking in the folder.
  bundle_id=$host_result
  [ -n "$bundle_id" ] || die_stopped "the backup did not report which bundle it wrote."

  log "Stopping PostgreSQL ${old_major} and setting its data aside..."
  docker stop "$old_server" >/dev/null
  old_server=""
  upgrade_phase=moving
  marker=$(printf 'major=%s\nconfig=%s\nputback=%s' "$old_major" "$(old_config_hint)" "$putback_cmd")
  # The marker goes in first, so a move that stops part-way is still found.
  # shellcheck disable=SC2016
  if ! vol_sh 'set -e; printf "%s\n" "$3" > "/v/$2"; set -- "$1" "$2" "$4"; '"$move_script" \
    "$aside" "$UPGRADE_MARKER" "$marker" "$old_dir"; then
    warn "could not set the PostgreSQL ${old_major} data aside"
    upgrade_rollback_help
    exit 1
  fi

  log "Starting PostgreSQL ${target_major}..."
  # --no-deps: db-version-check refuses to start the database while the
  # marker says an upgrade is in progress, which is exactly what this is.
  if ! docker compose up -d --wait --no-deps db >/dev/null 2>&1; then
    warn "PostgreSQL ${target_major} did not start; check: docker compose logs db"
    upgrade_rollback_help
    exit 1
  fi

  # Reach the new server by its container name on its own network: a "db"
  # alias on a network shared with other projects could be another server.
  new_db=$(docker compose ps -q db 2>/dev/null | head -n 1)
  new_db_name=$(docker inspect -f '{{.Name}}' "$new_db" 2>/dev/null | sed 's|^/||')
  # shellcheck disable=SC2016
  new_db_net=$(docker inspect -f '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}}{{"\n"}}{{end}}' "$new_db" 2>/dev/null | sed -n '1p')
  if [ -z "$new_db_name" ] || [ -z "$new_db_net" ]; then
    warn "cannot find the PostgreSQL ${target_major} container and its network"
    upgrade_rollback_help
    exit 1
  fi
  # A new server first runs a temporary one without TCP to set itself up, and
  # the healthcheck can pass on that one. Wait for the port the app uses.
  db_port=$(env_of DB_PORT)
  tries=0
  until docker exec "$new_db" pg_isready -q -h 127.0.0.1 -p "${db_port:-5432}" 2>/dev/null; do
    tries=$((tries + 1))
    if [ "$tries" -ge 30 ]; then
      warn "PostgreSQL ${target_major} does not accept connections on port ${db_port:-5432}; check: docker compose logs db"
      upgrade_rollback_help
      exit 1
    fi
    sleep 2
  done

  restore_status=0
  # The uploaded files are in place already; only the database moves.
  SURE_HOST_IMAGE=$tool_image SURE_HOST_DB=$new_db_name SURE_HOST_NETWORK=$new_db_net SURE_RECOVER=1 \
    host_run restore "$bundle_id" --yes --database-only || restore_status=$?
  if [ "$restore_status" -ne 0 ]; then
    warn "restoring into PostgreSQL ${target_major} failed"
    upgrade_rollback_help
    exit 1
  fi

  # shellcheck disable=SC2016
  vol_sh 'rm -f "/v/$1"' "$UPGRADE_MARKER" \
    || warn "could not remove ${UPGRADE_MARKER} from the volume ${volume}. The upgrade succeeded; remove it with: docker run --rm -v ${volume}:/v alpine rm /v/${UPGRADE_MARKER}"
  upgrade_phase=restored

  log "Starting Sure..."
  if ! up_output=$(docker compose up -d 2>&1); then
    printf '%s\n' "$up_output" >&2
    warn "the database is now on PostgreSQL ${target_major}, but Sure did not start; see above and: docker compose ps"
    warn "  Backup taken before the upgrade: ${bundle_id}"
    warn "  Old PostgreSQL ${old_major} data: kept in the volume ${volume}, folder ${aside}/"
    exit 1
  fi

  log ""
  log "Sure now runs on PostgreSQL ${target_major}."
  log "  Backup taken before the upgrade: ${bundle_id}"
  log "  Old PostgreSQL ${old_major} data: kept in the volume ${volume}, folder ${aside}/"
  log "  Once you are happy, free the space with:"
  log "    docker run --rm -v ${volume}:/v alpine rm -rf /v/${aside}"
}

command=${1:-daemon}
[ $# -gt 0 ] && shift

# On the host, run the database work in a container (see host_run).
if on_host; then
  case "$command" in
    create | restore | prune | scheduled)
      host_run "$command" "$@"
      exit $?
      ;;
    list)
      dir=$(env_get .env BACKUP_DIR)
      BACKUP_DIR=${dir:-./backups}
      ;;
  esac
fi

case "$command" in
  daemon) cmd_daemon ;;
  create) cmd_create "$@" ;;
  scheduled) cmd_scheduled ;;
  list) cmd_list ;;
  restore) cmd_restore "$@" ;;
  recover) cmd_recover "$@" ;;
  upgrade-postgres) cmd_upgrade_postgres "$@" ;;
  prune) ensure_deps; cmd_prune ;;
  -h | --help | help) usage ;;
  *) usage; exit 1 ;;
esac
