#!/bin/bash

installResticHost()
{
    if ! command -v restic >/dev/null 2>&1; then
        isHeader "Installing restic backup engine"
        resticInstall
    fi

    installResticMigrateLegacyPasswords

    if declare -f backupLocationsMigrate >/dev/null 2>&1; then
        backupLocationsMigrate
    fi

    if [[ -n "$(resticEnabledLocations)" ]]; then
        engineInitAllLocations
    else
        isNotice "No locations enabled — skipping init. Add one via the Locations page to start."
    fi
}

installResticMigrateLegacyPasswords()
{
    local pass_dir="${configs_dir}security/restic"
    [[ ! -d "$pass_dir" ]] && return 0

    declare -A legacy_map=(
        [local]=1
        [remote_1]=2
        [remote_2]=3
    )

    local old new
    for old in "${!legacy_map[@]}"; do
        local new="${legacy_map[$old]}"
        if [[ -f "$pass_dir/${old}.pass" && ! -f "$pass_dir/loc_${new}.pass" ]]; then
            sudo mv "$pass_dir/${old}.pass" "$pass_dir/loc_${new}.pass"
            isNotice "Migrated legacy password ${old}.pass → loc_${new}.pass"
        fi
    done
}
