#!/bin/bash

# Reconcile a live config file against its template (the freshly-cloned repo):
#   - keep the user's existing value for any key the template still defines
#   - add new template keys                     (CFG_REQUIREMENT_CONFIGS_AUTO_UPDATE)
#   - drop keys the template no longer defines  (CFG_REQUIREMENT_CONFIGS_AUTO_DELETE)
# Structure, ordering and comments follow the template. Non-interactive, atomic,
# and keeps a <file>.bak. Refuses to act on a missing/empty template so a broken
# clone can never wipe a live config.
reconcileConfigFile()
{
    local live="$1" template="$2"
    local do_add="${CFG_REQUIREMENT_CONFIGS_AUTO_UPDATE:-true}"
    local do_delete="${CFG_REQUIREMENT_CONFIGS_AUTO_DELETE:-true}"

    [[ -f "$live" ]] || return 0
    runInstallOp test -s "$template" 2>/dev/null || return 0

    declare -A live_line emitted
    local line key
    while IFS= read -r line; do
        [[ "$line" =~ ^(CFG_[A-Za-z0-9_]+)= ]] && live_line["${BASH_REMATCH[1]}"]="$line"
    done < <(runInstallOp cat "$live")

    local tmp; tmp=$(mktemp)
    while IFS= read -r line; do
        if [[ "$line" =~ ^(CFG_[A-Za-z0-9_]+)= ]]; then
            key="${BASH_REMATCH[1]}"
            if [[ -n "${live_line[$key]+x}" ]]; then
                printf '%s\n' "${live_line[$key]}" >> "$tmp"     # keep the user's value
                emitted["$key"]=1
            elif [[ "$do_add" == "true" ]]; then
                printf '%s\n' "$line" >> "$tmp"                  # new key, template default
            fi
        else
            printf '%s\n' "$line" >> "$tmp"                      # comments / blanks / ordering
        fi
    done < <(runInstallOp cat "$template")

    if [[ "$do_delete" != "true" ]]; then                       # keep keys the template dropped
        for key in "${!live_line[@]}"; do
            [[ -n "${emitted[$key]+x}" ]] || printf '%s\n' "${live_line[$key]}" >> "$tmp"
        done
    fi

    # Replace only when the result is sane (non-empty, has keys) and differs.
    if [[ -s "$tmp" ]] && grep -q '^CFG_' "$tmp" && ! runInstallOp cmp -s "$tmp" "$live"; then
        runInstallOp cp -a "$live" "${live}.bak"
        runInstallOp cp "$tmp" "$live"
        isSuccessful "Reconciled config: $(basename "$live")  (backup: $(basename "$live").bak)"
    fi
    rm -f "$tmp"
}

checkConfigFilesMissingVariables()
{
    local showheader="$1"

    [[ "$CFG_REQUIREMENT_CONFIGS_CHECK" == "true" ]] || return 0
    [[ "$showheader" == "true" ]] && isHeader "Scanning Config Files"
    isNotice "Reconciling config files against templates...please wait"

    checkLibrePortalConfigFilesMissingVariables;
    checkApplicationsConfigFilesMissingVariables;
}
