#!/usr/bin/env bash
# app-backup — back up the application database (custom-format dump) and,
# optionally, the file store.
#
# Usage: app-backup [options]
#   --all                include cache-table data (default: exclude EXCLUDE_TABLE_DATA)
#   --with-files         also archive DATA_DIR as <db>-<ts>-files.tar.gz (requires DATA_DIR)
#   --pre-update <label> tag the dump as a pre-update backup:
#                        <db>-<ts>-preupdate-<label>.dump. Pre-update dumps are
#                        NOT age-pruned; the newest BACKUP_KEEP_PREUPDATE of them
#                        are kept instead (used by app-deploy before activation)
#   --config <path>      use a specific config file
#   --show-config        print resolved configuration and exit
#   -h, --help           this help
#
# This is the engine's stock single-database backup. A multi-database app calls
# lib/backup.sh's de_dump_db() per database from its own script. Configuration:
# see common.sh / the per-app config template.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# help = the header comment block above, printed until the first non-# line. The
# generic command names (app-backup, app-deploy, …) are rewritten to THIS script's
# own name/prefix, so a renamed <product>-backup — or a custom CLI sourcing the
# libs — prints the right names with no install-time edit. pfx='app' (a no-op)
# when not renamed.
usage() {
    local cmd pfx; cmd="$(basename -- "$0")"; pfx="${cmd%-backup}"
    sed -n '2,${/^#/!q;s/^# \{0,1\}//;s/^#$//;p}' "$0" \
        | sed -E "s/app-(deploy|backup|health|update)/$pfx-\1/g"
}

INCLUDE_ALL=0; WITH_FILES=0; SHOW_CONFIG=0; PRE_UPDATE=""
while [ $# -gt 0 ]; do
    case "$1" in
        --all)          INCLUDE_ALL=1 ;;
        --with-files)   WITH_FILES=1 ;;
        --pre-update)   PRE_UPDATE="$2"; shift ;;
        --pre-update=*) PRE_UPDATE="${1#*=}" ;;
        --config)       CONFIG_FILE="$2"; shift ;;
        --config=*)     CONFIG_FILE="${1#*=}" ;;
        --show-config)  SHOW_CONFIG=1 ;;
        -h|--help)      usage; exit 0 ;;
        *)              echo "Unknown option: $1" >&2; exit 2 ;;
    esac
    shift
done

. "$SCRIPT_DIR/common.sh"
. "$SCRIPT_DIR/lib/backup.sh"

if [ "$SHOW_CONFIG" = 1 ]; then de_show_config; exit 0; fi

run_backup
