#!/bin/bash

# Generate data/peers/generated/peers.json — drives the /peers WebUI page and
# is also read by the /backup/migrate tab to overlay friendly names on top of
# bare hostnames.
#
# This is just peerList wrapped with a generated_at envelope; no extra logic.

webuiGeneratePeers()
{
    local output_dir="$containers_dir/libreportal/frontend/data/peers/generated"
    local output_file="$output_dir/peers.json"
    local temp_file="${output_file}.tmp.$$"

    runFileOp mkdir -p "$output_dir"

    local generated_at
    generated_at=$(date -Iseconds)
    local peers
    peers=$(peerList 2>/dev/null)
    [[ -z "$peers" ]] && peers='[]'

    cat > "$temp_file" <<EOF
{
  "generated_at": "$generated_at",
  "peers": $peers
}
EOF
    runFileOp mv "$temp_file" "$output_file"
    runFileOp chmod 644 "$output_file" 2>/dev/null || true
}
