#!/bin/bash

# Sync each scripts/backup/engines/*.json file into the WebUI data tree so the
# Configuration page's "Engine details" modal can fetch it. Source of truth is
# the bash-side JSON; the frontend never edits these.

webuiGenerateBackupEngines()
{
    local src_dir="$install_scripts_dir/backup/engines"
    local out_dir="$containers_dir/libreportal/frontend/data/backup/generated/engines"
    runFileOp mkdir -p "$out_dir"

    if [[ ! -d "$src_dir" ]]; then
        isNotice "No engines directory at $src_dir — skipping engines regen"
        return 0
    fi

    local index="["
    local first=true
    local f
    for f in "$src_dir"/*.json; do
        [[ -f "$f" ]] || continue
        local base
        base=$(basename "$f")
        runFileOp cp "$f" "$out_dir/$base"
        local id="${base%.json}"
        $first || index+=","
        first=false
        index+="\"$id\""
    done
    index+="]"

    local idx_file="$out_dir/index.json"
    echo "{\"engines\":$index,\"generated_at\":\"$(date -Iseconds)\"}" | runFileWrite "$idx_file"

    isSuccessful "Engines JSON regenerated"
}
