#!/bin/bash

resticSnapshotsJson()
{
    local idx="$1"
    local app_filter="$2"
    local host_filter="$3"

    resticEnvExport "$idx" || return 1

    local args=(snapshots --json --no-lock)
    [[ -n "$app_filter" ]]  && args+=(--tag "app=$app_filter")
    [[ -n "$host_filter" ]] && args+=(--host "$host_filter")

    runBackupOp restic "${args[@]}" 2>/dev/null
    local rc=$?
    resticEnvUnset
    return $rc
}

resticSystemSnapshotsJson()
{
    local idx="$1"
    local host_filter="$2"

    resticEnvExport "$idx" || return 1

    local args=(snapshots --json --no-lock --tag "system=config")
    [[ -n "$host_filter" ]] && args+=(--host "$host_filter")

    runBackupOp restic "${args[@]}" 2>/dev/null
    local rc=$?
    resticEnvUnset
    return $rc
}

resticSnapshotLatestId()
{
    local idx="$1"
    local app_name="$2"
    local host="${3:-$CFG_INSTALL_NAME}"

    resticEnvExport "$idx" || return 1
    local id
    id=$(runBackupOp restic snapshots \
        --tag "app=$app_name" --host "$host" \
        --latest 1 --json --no-lock 2>/dev/null | \
        grep -o '"short_id":"[^"]*"' | head -1 | cut -d'"' -f4)
    resticEnvUnset
    echo "$id"
}

resticSnapshotListFiles()
{
    local idx="$1"
    local snapshot_id="$2"

    resticEnvExport "$idx" || return 1
    runBackupOp restic ls --json --no-lock "$snapshot_id" 2>/dev/null
    local rc=$?
    resticEnvUnset
    return $rc
}
