#!/bin/bash

migrateSystem()
{
    local source_host="$1"
    local idx="$2"

    if [[ -z "$source_host" ]]; then
        isError "migrateSystem requires source_host"
        return 1
    fi

    [[ -z "$idx" ]] && idx=$(resticEnabledLocations | head -1)

    isHeader "Migrating entire system from host=$source_host"

    local apps_json
    apps_json=$(engineSnapshotsJson "$idx" "" "$source_host")
    if [[ -z "$apps_json" || "$apps_json" == "[]" ]]; then
        isError "No snapshots found in $(resticLocationName "$idx") for host=$source_host"
        return 1
    fi

    local apps=()
    while IFS= read -r app; do
        [[ -n "$app" ]] && apps+=("$app")
    done < <(echo "$apps_json" | grep -o '"app=[^"]*"' | sort -u | sed 's/"app=\(.*\)"/\1/')

    if [[ ${#apps[@]} -eq 0 ]]; then
        isError "Could not parse app list from snapshots"
        return 1
    fi

    isNotice "Apps to migrate: ${apps[*]}"
    for app in "${apps[@]}"; do
        migrateApp "$app" "$source_host" "$idx"
    done

    isSuccessful "System migration complete — ${#apps[@]} apps"
}
