#!/bin/bash

kopiaCheckLocation()
{
    local idx="$1"
    local read_data="$2"

    kopiaEnvExport "$idx" || return 1

    local args=(content verify)
    if [[ "$read_data" == "full" ]]; then
        args+=(--verify-data-percent=100)
    elif [[ -n "$read_data" ]]; then
        args+=(--verify-data-percent="$read_data")
    fi

    isNotice "Checking $(resticLocationName "$idx") with Kopia${read_data:+ (data sample: ${read_data}%)}"
    runBackupOp kopia "${args[@]}"
    local rc=$?
    kopiaEnvUnset
    if [[ $rc -eq 0 ]]; then
        isSuccessful "$(resticLocationName "$idx") integrity OK"
    else
        isError "$(resticLocationName "$idx") integrity FAILED"
    fi
    return $rc
}

kopiaLocationStats()
{
    local idx="$1"
    kopiaEnvExport "$idx" || return 1
    local raw
    raw=$(runBackupOp kopia repository status --json 2>/dev/null)
    kopiaEnvUnset
    [[ -z "$raw" ]] && { echo '{"total_size":0,"total_file_count":0}'; return 0; }

    if command -v jq >/dev/null 2>&1; then
        echo "$raw" | jq -c '{
            total_size:       (.contentStats.totalSize // 0),
            total_file_count: (.contentStats.totalCount // 0)
        }'
    else
        echo '{"total_size":0,"total_file_count":0}'
    fi
}
