#!/bin/bash

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

    if [[ -z "$idx" || -z "$snapshot_id" ]]; then
        isError "backupAppDeleteSnapshot requires location idx and snapshot_id"
        return 1
    fi

    if resticLocationAppendOnly "$idx"; then
        isError "$(resticLocationName "$idx") is append-only — refusing to delete snapshot"
        return 1
    fi

    resticEnvExport "$idx" || return 1
    runBackupOp restic forget "$snapshot_id" $([[ "$CFG_BACKUP_PRUNE_AFTER_FORGET" == "true" ]] && echo "--prune")
    local rc=$?
    resticEnvUnset
    if [[ $rc -eq 0 ]]; then
        isSuccessful "Snapshot ${snapshot_id:0:8} removed from $(resticLocationName "$idx")"
    else
        isError "Failed to remove snapshot ${snapshot_id:0:8} from $(resticLocationName "$idx")"
    fi
    return $rc
}

backupAppDeleteAll()
{
    local app_name="$1"

    if [[ -z "$app_name" ]]; then
        isError "backupAppDeleteAll requires app_name"
        return 1
    fi

    isHeader "Deleting ALL snapshots for $app_name"
    isNotice "Append-only locations will be skipped."

    local idx
    while IFS= read -r idx; do
        [[ -z "$idx" ]] && continue
        if resticLocationAppendOnly "$idx"; then
            isNotice "Skipping append-only $(resticLocationName "$idx")"
            continue
        fi
        resticEnvExport "$idx" || continue
        runBackupOp restic forget --tag "app=$app_name" $([[ "$CFG_BACKUP_PRUNE_AFTER_FORGET" == "true" ]] && echo "--prune")
        resticEnvUnset
    done < <(resticEnabledLocations)
}
