#!/bin/bash

webuiGenerateBackupSnapshots()
{
    local scope="${1:-all}"
    local output_dir="$containers_dir/libreportal/frontend/data/backup/generated"
    runFileOp mkdir -p "$output_dir"

    local indices=()
    if [[ "$scope" == "all" ]]; then
        while IFS= read -r i; do
            [[ -n "$i" ]] && indices+=("$i")
        done < <(resticEnabledLocations)
    else
        indices+=("$scope")
    fi

    for idx in "${indices[@]}"; do
        local output_file="$output_dir/snapshots_${idx}.json"
        local temp_file="${output_file}.tmp.$$"

        local raw
        raw=$(engineSnapshotsJson "$idx" 2>/dev/null)
        if [[ -z "$raw" ]]; then
            raw="[]"
        fi

        local content="{"
        content+="\"location_idx\":$idx,"
        content+="\"location_name\":\"$(printf '%s' "$(resticLocationName "$idx")" | sed 's/\\/\\\\/g; s/"/\\"/g')\","
        content+="\"generated_at\":\"$(date -Iseconds)\","
        content+="\"snapshots\":$raw"
        content+="}"

        echo "$content" | runFileWrite "$output_file"
    done

    isSuccessful "Snapshots JSON regenerated (${#indices[@]} location(s))"
}
