#!/bin/bash

webuiGenerateBackupLocations()
{
    local output_dir="$containers_dir/libreportal/frontend/data/backup/generated"
    local output_file="$output_dir/locations.json"
    local temp_file="${output_file}.tmp.$$"
    runFileOp mkdir -p "$output_dir"

    if declare -f backupLocationsMigrate >/dev/null 2>&1; then
        backupLocationsMigrate >/dev/null 2>&1 || true
    fi

    if declare -f engineEnsureAllLocationsReady >/dev/null 2>&1; then
        engineEnsureAllLocationsReady >/dev/null 2>&1 || true
    fi

    local content="{"
    content+="\"generated_at\":\"$(date -Iseconds)\","
    content+="\"locations\":["

    local first=true
    local idx
    while IFS= read -r idx; do
        [[ -z "$idx" ]] && continue
        local name enabled type uri append_only custom_retention engine
        name=$(resticLocationName "$idx")
        enabled="false"; resticLocationEnabled "$idx" && enabled="true"
        type=$(resticLocationType "$idx")
        uri=$(resticLocationUri "$idx")
        append_only="false"; resticLocationAppendOnly "$idx" && append_only="true"
        custom_retention="false"
        [[ "$(resticLocationField "$idx" CUSTOM_RETENTION)" == "true" ]] && custom_retention="true"
        engine=$(engineForLocation "$idx")

        local pass_value pass_exists
        pass_value=$(resticLocationPassword "$idx")
        pass_exists="false"
        if [[ -n "$pass_value" && "$pass_value" != RANDOMIZEDPASSWORD* ]]; then
            pass_exists="true"
        fi

        local total_size="0" total_files="0"
        if [[ "$enabled" == "true" && "$pass_exists" == "true" ]]; then
            local stats_json
            stats_json=$(engineLocationStats "$idx" 2>/dev/null)
            if [[ -n "$stats_json" ]]; then
                total_size=$(echo "$stats_json" | grep -o '"total_size":[0-9]*' | head -1 | cut -d':' -f2)
                total_files=$(echo "$stats_json" | grep -o '"total_file_count":[0-9]*' | head -1 | cut -d':' -f2)
                [[ -z "$total_size" ]] && total_size="0"
                [[ -z "$total_files" ]] && total_files="0"
            fi
        fi

        # SSH key state for sftp key auth. Only the PUBLIC key is exposed (safe
        # to share — it's what goes in the remote's authorized_keys); the
        # private key never leaves the location's ssh.key file.
        local ssh_key_exists="false" ssh_public_key=""
        if declare -f backupSshKeyExists >/dev/null 2>&1 && backupSshKeyExists "$idx"; then
            ssh_key_exists="true"
            ssh_public_key=$(backupSshKeyPublic "$idx" 2>/dev/null)
        fi
        local ssh_pub_esc
        ssh_pub_esc=$(printf '%s' "$ssh_public_key" | sed 's/\\/\\\\/g; s/"/\\"/g')

        local name_esc uri_esc
        name_esc=$(printf '%s' "$name" | sed 's/\\/\\\\/g; s/"/\\"/g')
        uri_esc=$(printf '%s' "$uri" | sed 's/\\/\\\\/g; s/"/\\"/g')

        $first || content+=","
        first=false
        content+="{"
        content+="\"idx\":$idx,"
        content+="\"name\":\"$name_esc\","
        content+="\"enabled\":$enabled,"
        content+="\"engine\":\"$engine\","
        content+="\"type\":\"$type\","
        content+="\"uri\":\"$uri_esc\","
        content+="\"append_only\":$append_only,"
        content+="\"custom_retention\":$custom_retention,"
        content+="\"password_exists\":$pass_exists,"
        content+="\"total_size_bytes\":$total_size,"
        content+="\"total_files\":$total_files,"
        content+="\"path\":\"$(printf '%s' "$(resticLocationField "$idx" PATH)"      | sed 's/\\/\\\\/g; s/"/\\"/g')\","
        content+="\"path_mode\":\"$(resticLocationField "$idx" PATH_MODE)\","
        content+="\"ssh_user\":\"$(printf '%s' "$(resticLocationField "$idx" SSH_USER)" | sed 's/\\/\\\\/g; s/"/\\"/g')\","
        content+="\"ssh_host\":\"$(printf '%s' "$(resticLocationField "$idx" SSH_HOST)" | sed 's/\\/\\\\/g; s/"/\\"/g')\","
        content+="\"ssh_port\":\"$(resticLocationField "$idx" SSH_PORT)\","
        content+="\"ssh_path\":\"$(printf '%s' "$(resticLocationField "$idx" SSH_PATH)" | sed 's/\\/\\\\/g; s/"/\\"/g')\","
        content+="\"ssh_auth\":\"$(resticLocationField "$idx" SSH_AUTH)\","
        content+="\"ssh_key_exists\":$ssh_key_exists,"
        content+="\"ssh_public_key\":\"$ssh_pub_esc\","
        content+="\"keep_last\":\"$(resticLocationField "$idx" KEEP_LAST)\","
        content+="\"keep_daily\":\"$(resticLocationField "$idx" KEEP_DAILY)\","
        content+="\"keep_weekly\":\"$(resticLocationField "$idx" KEEP_WEEKLY)\","
        content+="\"keep_monthly\":\"$(resticLocationField "$idx" KEEP_MONTHLY)\","
        content+="\"keep_yearly\":\"$(resticLocationField "$idx" KEEP_YEARLY)\""
        content+="}"
    done < <(resticAllLocationIndices)
    content+="]}"

    echo "$content" | runFileWrite "$output_file"
    isSuccessful "Locations JSON regenerated"
}
