#!/bin/bash

# Per-app migrate hooks. After a migrate (restic-mediated apply OR direct-SSH
# pull) places the source's data on this host, some apps need app-specific
# fix-ups beyond the standard URL rewrite — rotating a federation key,
# regenerating an OIDC client secret, dropping a SaaS lock, etc.
#
# Convention: an app's tools.sh (auto-sourced by the modular per-app tools
# loader — see [[libreportal-modular-app-tools]]) may declare:
#
#   <app>_migrate_pre()       # called before stop+wipe
#   <app>_migrate_post()      # called after restart, before user sees it
#
# Both receive: $1 = source_hostname (peer hostname or backup tag),
#               $2 = transport ("restic" | "direct-ssh")
# Hooks are optional — apps without them just inherit the standard flow.

# Run a single named hook if it exists. Quiet if not defined.
migrateRunHook()
{
    local app="$1"
    local stage="$2"           # "pre" or "post"
    local source="$3"
    local transport="$4"

    local hook_name="${app}_migrate_${stage}"
    if declare -f "$hook_name" >/dev/null 2>&1; then
        isNotice "Running ${stage}-migrate hook for ${app}"
        migrateEmit phase="hook-${stage}" status=running app="$app" hook="$hook_name"
        if "$hook_name" "$source" "$transport"; then
            migrateEmit phase="hook-${stage}" status=complete app="$app"
        else
            isNotice "Hook ${hook_name} returned non-zero — continuing migrate"
            migrateEmit phase="hook-${stage}" status=failed app="$app"
        fi
    fi
}
