#!/bin/bash

webuiGenerateBackupAppStatus()
{
    local app_name="$1"
    local output_dir="$containers_dir/libreportal/frontend/data/backup/generated/apps"
    runFileOp mkdir -p "$output_dir"

    if [[ -z "$app_name" ]]; then
        if [[ -f "$docker_dir/$db_file" ]]; then
            while IFS= read -r a; do
                [[ -n "$a" ]] && webuiGenerateBackupAppStatus "$a"
            done < <(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT name FROM apps WHERE status = 1;" 2>/dev/null)
        fi
        return 0
    fi

    local output_file="$output_dir/${app_name}.json"
    local temp_file="${output_file}.tmp.$$"

    local content="{"
    content+="\"app\":\"$app_name\","
    content+="\"generated_at\":\"$(date -Iseconds)\","
    content+="\"host\":\"${CFG_INSTALL_NAME:-libreportal}\","
    content+="\"snapshots\":["

    local first=true
    local idx
    while IFS= read -r idx; do
        [[ -z "$idx" ]] && continue
        local snaps
        snaps=$(engineSnapshotsJson "$idx" "$app_name" "$CFG_INSTALL_NAME" 2>/dev/null)
        [[ -z "$snaps" || "$snaps" == "[]" ]] && continue
        local count latest_id latest_time
        count=$(echo "$snaps" | grep -o '"short_id"' | wc -l | tr -d ' ')
        latest_id=$(echo "$snaps" | grep -o '"short_id":"[^"]*"' | tail -1 | cut -d'"' -f4)
        latest_time=$(echo "$snaps" | grep -o '"time":"[^"]*"' | tail -1 | cut -d'"' -f4)

        local name_esc
        name_esc=$(printf '%s' "$(resticLocationName "$idx")" | sed 's/\\/\\\\/g; s/"/\\"/g')

        $first || content+=","
        first=false
        content+="{"
        content+="\"location_idx\":$idx,"
        content+="\"location_name\":\"$name_esc\","
        content+="\"count\":$count,"
        content+="\"latest_id\":\"$latest_id\","
        content+="\"latest_time\":\"$latest_time\""
        content+="}"
    done < <(resticEnabledLocations)
    content+="]}"

    echo "$content" | runFileWrite "$output_file"
}
