#!/bin/bash

# System-config backup.
#
# Snapshots the system config tree (<system>/configs — global settings, WebUI
# credentials, and crucially the BACKUP-LOCATION credentials) to every enabled
# backup location, so a bare-metal restore is self-sufficient. Without this the
# location creds live only on the box: lose it and you can't even reach your own
# remote backups (chicken-and-egg). It is a lightweight, static-dir snapshot — no
# container quiescing or DB dumps (those are per-app concerns), so it does NOT go
# through backupAppStart. The install tree (code) is reproducible from the release
# and is deliberately NOT included; per-app data is handled by backupAppStart.

backupSystemConfig()
{
    local source_path="${configs_dir%/}"
    if [[ ! -d "$source_path" ]]; then
        isNotice "System config dir not found ($source_path) — skipping system backup"
        return 0
    fi
    if [[ -z "$(resticEnabledLocations)" ]]; then
        isNotice "No backup locations enabled — skipping system config backup"
        return 0
    fi

    isHeader "Backing up system config"
    engineEnsureAllLocationsReady

    local idx ok=0 fail=0
    while IFS= read -r idx; do
        [[ -z "$idx" ]] && continue
        if engineBackupSystem "$idx" >/dev/null; then
            ok=$((ok + 1))
        else
            fail=$((fail + 1))
        fi
    done < <(resticEnabledLocations)

    if [[ $ok -eq 0 ]]; then
        isError "System config backup failed on all locations"
        return 1
    fi

    # Apply retention so system snapshots don't accumulate (respects append-only
    # locations; bypasses backupAppStart's per-app forget, so do it here).
    while IFS= read -r idx; do
        [[ -z "$idx" ]] && continue
        engineForgetSystem "$idx" >/dev/null 2>&1 || true
    done < <(resticEnabledLocations)

    if [[ $fail -gt 0 ]]; then
        isNotice "System config backed up to $ok location(s), failed on $fail"
    else
        isSuccessful "System config backed up to $ok location(s)"
    fi
    return 0
}

# Restore the latest system-config snapshot from a location into a STAGING dir.
# Deliberately does NOT overwrite live config — recovering creds/settings is a
# review-then-copy step, never an automatic blast over a running control plane.
backupRestoreSystemConfig()
{
    local idx="${1:-}"
    [[ -z "$idx" ]] && idx=$(resticEnabledLocations | head -1)
    if [[ -z "$idx" ]]; then
        isError "No enabled backup location to restore the system config from"
        return 1
    fi

    local staging="${restore_dir%/}/system-config"
    runFileOp mkdir -p "$staging"

    isHeader "Restoring system config (to staging — live config is untouched)"
    if engineRestoreSystemLatest "$idx" "$staging"; then
        isSuccessful "System config restored to: $staging"
        isNotice "Review it, then copy what you need into ${configs_dir} (backup-location creds, logins, settings). Live config was NOT overwritten."
        return 0
    fi
    isError "System config restore failed"
    return 1
}
