#!/bin/bash
# ==============================================================================================
# ============================= Conf Cache Restore =============================================
# ==============================================================================================
#
# PURPOSE
# ─────────────────────────────────────────────────────────────────────────────
# Runs at array start after conf_sync.sh. Checks whether partner confs made it
# into the RAM cache. If any are missing (partner was unreachable at boot) and
# a persistent backup exists from the previous shutdown, loads the missing confs
# from backup into the RAM cache so scripts like fallback.sh have partner vars.
#
# Always removes the persistent backup when done — used or not.
#
# Normal reboot (partner up):
#   conf_sync.sh pulls fresh → RAM cache complete → backup not needed → removed
#
# Edge case (partner down at boot):
#   conf_sync.sh fails to pull → RAM cache missing partner → backup loaded into
#   RAM → backup removed → fallback.sh runs with last-known-good partner vars
#
# Own conf is never in the backup — it's always on disk.
#
# ==============================================================================================
# OPERATIONAL MODEL
# ==============================================================================================
#
#   1. Gates — PARTNERSHIP_ENABLED, and a validated PERSISTENT_CONF_CACHE path
#   2. No backup directory → exit 0, nothing to restore
#   3. For each host*.conf in the backup:
#        own conf              → skip (always on disk)
#        already in RAM cache  → skip — conf_sync.sh reached the partner, its copy
#                                is fresher than this one
#        otherwise             → copy into the RAM cache, mode 600
#   4. Clear the backup unconditionally — see Remove After Use below
#
# Counterpart to conf_cache_save.sh, which writes this backup at array stop.
#
# ==============================================================================================
# DESIGN PRINCIPLES
# ==============================================================================================
#
# Remove After Use
#   The persistent backup is always removed at the end of the run — whether it
#   was used or not. Stale backups from a previous shutdown should never be left
#   behind as a permanent fallback; the backup is a single-boot safety net, not
#   a long-lived cache.
#
# Partner Only
#   Own conf is on disk and is always available regardless of array or partner
#   state. Only partner confs can be missing after a boot — only those are
#   restored.
#
# ==============================================================================================
# OPERATIONAL SAFEGUARDS
# ==============================================================================================
#
# Root Enforcement
#   Reads the plugin-directory backup and writes the RAM cache.
#
# Lock Acquisition
#   acquire_lock prevents this racing conf_cache_save.sh or the conf cache watchdog
#   over the same backup directory — this script deletes it at the end.
#
# Partnership Gate
#   require_partnership exits early if PARTNERSHIP_ENABLED=false.
#
# Host Detection
#   detect_hosts() determines which conf files are partner confs and which is our own.
#
# Cache Path Sanity Guard
#   PERSISTENT_CONF_CACHE is validated as an absolute path at least three levels deep
#   before anything is read or removed. This script ends with rm -rf on that path, and
#   the directory-exists check alone would not catch a collapsed value — / is a
#   directory.
#
# No-Backup Guard
#   Exits cleanly if the backup directory does not exist — the normal case when the
#   partner was reachable at boot.
#
# Fresh-Copy Precedence
#   A conf already present in the RAM cache is never overwritten from the backup.
#   conf_sync.sh reaching the partner means its copy is current; the backup is by
#   definition older.
#
# Own-Conf Exclusion
#   Our own conf is never restored from the backup over the live on-disk copy.
#
# Credential File Permissions
#   The RAM cache directory is created 700 and each restored conf written 600 — these
#   carry partner NPM/lldap passwords and API keys and live under a world-readable /tmp.
#
# Dry Run Support
#   --dry-run reports what would be restored and removed, and changes nothing.
#
# ==============================================================================================
# CONFIGURATION
# ==============================================================================================
#
# master.conf
#
#   PERSISTENT_CONF_CACHE
#       Reboot-surviving backup written by conf_cache_save.sh. Consumed and cleared here.
#
#   CONF_RAM_CACHE_DIR
#       Destination RAM cache (tmpfs, /tmp/.cache/vv/d) that load_config.sh reads
#       partner vars from.
#
#   PARTNERSHIP_ENABLED
#       Checked via require_partnership().
#
# ==============================================================================================
# RUNTIME MODES
# ==============================================================================================
#
# conf_cache_restore.sh
#     Restore partner confs into the RAM cache, then clear the backup.
#     Runs at array start, after conf_sync.sh has had its chance.
#
# conf_cache_restore.sh --dry-run
#     Report what would be restored and removed without changing anything
#
# conf_cache_restore.sh --log
#     Verbose per-file output
#
# ==============================================================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../load_config.sh"

parse_args "$@"

if [[ "$EUID" -ne 0 ]]; then
    error "Must be run as root"
    exit 1
fi

acquire_lock

detect_hosts
require_partnership

RAM_CACHE="$CONF_RAM_CACHE_DIR"
SAVE_DIR="${PERSISTENT_CONF_CACHE:-}"

# SAVE_DIR is rm -rf'd at the end of this script and is built from ${SCRIPTS_DIR}. If that is
# ever unset the path collapses toward / — and the -d check below would pass, since / is a
# directory. Require an absolute path at least three levels deep before touching it.
_slashes="${SAVE_DIR//[^\/]/}"
if [[ -z "$SAVE_DIR" || "$SAVE_DIR" != /* || "${#_slashes}" -lt 3 ]]; then
    error "PERSISTENT_CONF_CACHE is unset or unsafe ('${SAVE_DIR:-unset}') — refusing to restore or clear"
    notify "conf_cache_restore aborted on $(hostname) — PERSISTENT_CONF_CACHE is '${SAVE_DIR:-unset}'" \
        "Conf Cache Restore" "warning"
    exit 1
fi
unset _slashes

[[ "$DRY_RUN" == true ]] && warn "DRY RUN — no changes will be made"

if [[ ! -d "$SAVE_DIR" ]]; then
    log "No persistent conf backup found — nothing to restore"
    exit 0
fi

restored=0
for conf in "$SAVE_DIR"/host*.conf; do
    [[ -f "$conf" ]] || continue
    base="$(basename "$conf")"
    is_own_conf_file "$base" && continue

    if [[ -f "$RAM_CACHE/$base" ]]; then
        log "$base already in RAM cache (conf_sync succeeded) — skipping"
        continue
    fi

    if [[ "$DRY_RUN" == true ]]; then
        warn "DRY RUN — would restore $base → RAM cache"
        (( restored++ ))
        continue
    fi

    # Partner confs carry credentials (NPM/lldap passwords, API keys). Default umask would
    # leave them 644 in a world-readable /tmp path — restrict on the way in, not afterwards.
    mkdir -p "$RAM_CACHE" && chmod 700 "$RAM_CACHE"
    if cp "$conf" "$RAM_CACHE/$base" && chmod 600 "$RAM_CACHE/$base"; then
        echo "Restored $base from persistent backup → RAM cache ✅"
        (( restored++ ))
    else
        warn "Failed to restore $base"
    fi
done

[[ "$restored" -gt 0 ]] && \
    warn "Loaded $restored partner conf(s) from persistent backup — partner was unreachable at array start"

if [[ "$DRY_RUN" == false ]]; then
    rm -rf "$SAVE_DIR"
    log "Persistent conf backup cleared"
else
    warn "DRY RUN — would remove $SAVE_DIR"
fi

exit 0
