#!/bin/bash

# Kopia retention is expressed as a per-source policy plus a maintenance pass.
# We set the policy on the path we backed up, then run maintenance which
# forgets and reclaims space in one go.

kopiaForgetApp()
{
    local idx="$1"
    local app_name="$2"

    if resticLocationAppendOnly "$idx"; then
        isNotice "$(resticLocationName "$idx") is append-only — skipping forget for $app_name"
        return 0
    fi

    local keep_last keep_daily keep_weekly keep_monthly keep_yearly
    keep_last=$(resticRetentionFor "$idx" KEEP_LAST)
    keep_daily=$(resticRetentionFor "$idx" KEEP_DAILY)
    keep_weekly=$(resticRetentionFor "$idx" KEEP_WEEKLY)
    keep_monthly=$(resticRetentionFor "$idx" KEEP_MONTHLY)
    keep_yearly=$(resticRetentionFor "$idx" KEEP_YEARLY)

    kopiaEnvExport "$idx" || return 1

    local src="$containers_dir$app_name"
    local host_tag="${CFG_INSTALL_NAME:-libreportal}"

    local policy_args=(policy set --global=false "$src")
    [[ -n "$keep_last"    ]] && policy_args+=(--keep-latest "$keep_last")
    [[ -n "$keep_daily"   ]] && policy_args+=(--keep-daily "$keep_daily")
    [[ -n "$keep_weekly"  ]] && policy_args+=(--keep-weekly "$keep_weekly")
    [[ -n "$keep_monthly" ]] && policy_args+=(--keep-monthly "$keep_monthly")
    [[ -n "$keep_yearly"  ]] && policy_args+=(--keep-annual "$keep_yearly")

    runBackupOp kopia "${policy_args[@]}" >/dev/null 2>&1

    isNotice "Running Kopia maintenance for $app_name on $(resticLocationName "$idx")"
    runBackupOp kopia maintenance run --full
    local rc=$?
    kopiaEnvUnset
    return $rc
}

kopiaForgetSystem()
{
    local idx="$1"

    if resticLocationAppendOnly "$idx"; then
        isNotice "$(resticLocationName "$idx") is append-only — skipping forget for system config"
        return 0
    fi

    local keep_last keep_daily keep_weekly keep_monthly keep_yearly
    keep_last=$(resticRetentionFor "$idx" KEEP_LAST)
    keep_daily=$(resticRetentionFor "$idx" KEEP_DAILY)
    keep_weekly=$(resticRetentionFor "$idx" KEEP_WEEKLY)
    keep_monthly=$(resticRetentionFor "$idx" KEEP_MONTHLY)
    keep_yearly=$(resticRetentionFor "$idx" KEEP_YEARLY)

    kopiaEnvExport "$idx" || return 1

    local src="${configs_dir%/}"

    local policy_args=(policy set --global=false "$src")
    [[ -n "$keep_last"    ]] && policy_args+=(--keep-latest "$keep_last")
    [[ -n "$keep_daily"   ]] && policy_args+=(--keep-daily "$keep_daily")
    [[ -n "$keep_weekly"  ]] && policy_args+=(--keep-weekly "$keep_weekly")
    [[ -n "$keep_monthly" ]] && policy_args+=(--keep-monthly "$keep_monthly")
    [[ -n "$keep_yearly"  ]] && policy_args+=(--keep-annual "$keep_yearly")

    runBackupOp kopia "${policy_args[@]}" >/dev/null 2>&1

    isNotice "Running Kopia maintenance for system config on $(resticLocationName "$idx")"
    runBackupOp kopia maintenance run --full
    local rc=$?
    kopiaEnvUnset
    return $rc
}
