#!/bin/bash

cliHandleRestoreCommands()
{
    local restore_type="$initial_command2"
    local action="$initial_command3"
    local name="$initial_command4"
    local extra="$initial_command5"
    local extra2="$initial_command6"

    if [[ -z "$restore_type" ]]; then
        cliShowRestoreHelp
        return
    fi

    case "$restore_type" in
        app)
            case "$action" in
                ""|help) cliShowRestoreHelp ;;
                start)
                    [[ -z "$name" ]] && { isNotice "No app name provided."; cliShowRestoreHelp; return; }
                    restoreAppStart "$name" "${extra:-latest}" "$extra2"
                    ;;
                list)
                    [[ -z "$name" ]] && { isNotice "No app name provided."; cliShowRestoreHelp; return; }
                    local idx
                    while IFS= read -r idx; do
                        [[ -z "$idx" ]] && continue
                        echo "--- $(resticLocationName "$idx") (loc $idx) ---"
                        engineSnapshotsJson "$idx" "$name"
                    done < <(resticEnabledLocations)
                    ;;
                *)
                    isNotice "Invalid app restore action: $action"
                    cliShowRestoreHelp
                    ;;
            esac
            ;;
        migrate)
            case "$action" in
                app)
                    [[ -z "$name" ]] && { isNotice "Usage: restore migrate app <app_name> <source_host> [loc_idx]"; return; }
                    [[ -z "$extra" ]] && { isNotice "Usage: restore migrate app <app_name> <source_host> [loc_idx]"; return; }
                    migrateApp "$name" "$extra" "$extra2"
                    ;;
                system)
                    [[ -z "$name" ]] && { isNotice "Usage: restore migrate system <source_host> [loc_idx]"; return; }
                    migrateSystem "$name" "$extra"
                    ;;
                discover)
                    migrateDiscoverHosts "$name"
                    ;;
                *)
                    isNotice "Invalid migrate action: $action"
                    cliShowRestoreHelp
                    ;;
            esac
            ;;
        first-run)
            case "$action" in
                discover)
                    [[ -z "$name" ]] && name="1"
                    restoreFirstRunDiscover "$name"
                    ;;
                bulk)
                    [[ -z "$name" || -z "$extra" ]] && { isNotice "Usage: restore first-run bulk <loc_idx> <source_host> <app1> [app2 ...]"; return; }
                    local loc_idx="$name"
                    local source_host="$extra"
                    shift 4
                    restoreFirstRunBulk "$loc_idx" "$source_host" "$@"
                    ;;
                *) cliShowRestoreHelp ;;
            esac
            ;;
        *)
            isNotice "Invalid restore type: $restore_type"
            cliShowRestoreHelp
            ;;
    esac
}
