#!/bin/bash

backupAllApps()
{
    isHeader "Backing up all installed applications"

    if [ ! -f "$docker_dir/$db_file" ]; then
        isError "Database not found: $docker_dir/$db_file"
        return 1
    fi

    local app_names=()
    while IFS= read -r name; do
        app_names+=("$name")
    done < <(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT name FROM apps WHERE status = 1;")

    local done_count=0
    for name in "${app_names[@]}"; do
        # The libreportal WebUI app is reproducible — frontend + generated JSON
        # regenerate on deploy, and its only state (the login) lives in the system
        # config, captured by backupSystemConfig below. Nothing in its data dir is
        # worth a snapshot.
        if [[ "$name" == "libreportal" ]]; then
            isNotice "Skipping '$name' — WebUI is reproducible; its state is in the system config"
            continue
        fi
        backupAppStart "$name"
        ((done_count++))
    done

    # System config snapshot (global settings, WebUI creds, backup-location creds)
    # so a bare-metal restore is self-sufficient — this is why the system root is
    # its own backup-able tree. The code/install tree is reproducible from the
    # release, so it is deliberately NOT included.
    if declare -f backupSystemConfig >/dev/null 2>&1; then
        backupSystemConfig
    fi

    isSuccessful "Backup pass complete — ${done_count} app(s) + system config"
}
