#!/bin/bash

# Pre-migrate backup. Before the destination app gets wiped and replaced with
# the source's snapshot, take a fresh local backup of the destination's app —
# tagged with `pre-migrate=<timestamp>` so it's easy to find for rollback if
# the migrate misbehaves. Best-effort: emits a notice and continues if no
# backup location is available (the caller already warned the user via
# preflight).
#
# Args: <app_name> <loc_idx>  (loc_idx defaults to first enabled)
# Returns: 0 always (a missing pre-backup must never block the migrate; the
# user already saw and confirmed the preflight that warned about it).

migratePreBackupDestination()
{
    local app="$1"
    local idx="$2"

    if [[ -z "$app" ]]; then
        isError "migratePreBackupDestination: app required"
        migrateEmit phase=pre-backup status=skipped reason=no-app
        return 0
    fi

    # Only meaningful if the destination actually has this app installed.
    if [[ ! -d "$containers_dir$app" ]]; then
        isNotice "No existing $app on destination — pre-migrate backup skipped"
        migrateEmit phase=pre-backup status=skipped reason=no-existing-app app="$app"
        return 0
    fi

    if [[ -z "$idx" ]]; then
        idx=$(resticEnabledLocations | head -1)
    fi
    if [[ -z "$idx" ]]; then
        isNotice "No backup locations enabled — pre-migrate backup skipped"
        migrateEmit phase=pre-backup status=skipped reason=no-backup-location app="$app"
        return 0
    fi

    local stamp
    stamp=$(date -u +%Y%m%dT%H%M%SZ)
    isNotice "Pre-migrate backup of destination $app → $(resticLocationName "$idx") (tag pre-migrate=$stamp)"
    migrateEmit phase=pre-backup status=running app="$app" loc_idx="$idx" stamp="$stamp"

    # engineBackupApp takes (idx, app, [extra_tags...]). The pre-migrate tag
    # makes the snapshot trivially findable later: restic snapshots --tag pre-migrate
    if engineBackupApp "$idx" "$app" "pre-migrate=$stamp"; then
        isSuccessful "Pre-migrate backup of $app complete"
        migrateEmit phase=pre-backup status=complete app="$app" stamp="$stamp"
    else
        isNotice "Pre-migrate backup of $app FAILED — continuing migrate anyway (you confirmed)"
        migrateEmit phase=pre-backup status=failed app="$app" stamp="$stamp"
    fi

    return 0
}
