# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2024 SUSE LLC
# SPDX-FileCopyrightText: Copyright 2024 Richard Brown
# SPDX-FileCopyrightText: Copyright 2026 Tobias Görgens


. "${TIK_MIGRATION_LIBRARY:-/usr/lib/tik/lib/tik-migration-backup}"

tik_migration_current_discover() {
    local candidate="${TIK_ROOT_MNT}/home" candidates user_home fsroot
    [[ -d ${candidate} && ! -L ${candidate} ]] || return 0
    # A mounted Aeon/openSUSE shared home is handled by the legacy module even
    # when some of its user directories happen to be individual subvolumes.
    fsroot="$(findmnt --first-only --direction backward -nro FSROOT --target "${candidate}")"
    case ${fsroot} in /@home|/@/home) return 0 ;; esac
    candidates="$(prun /usr/bin/find "${candidate}" -mindepth 1 -maxdepth 1 \
        -type d ! -name '.*' -print)" || error "Cannot list source home directories."
    [[ -n ${candidates} ]] || return 0
    while IFS= read -r user_home; do
        prun-opt /usr/sbin/btrfs subvolume show "${user_home}" >/dev/null 2>&1
        if [[ ${retval} != 0 ]]; then
            home_subvolumes=() home_names=() home_is_subvolume=()
            home_list=""
            return 0
        fi
        home_subvolumes+=("${user_home}")
        home_names+=("${user_home##*/}")
        home_is_subvolume+=(1)
        home_list="${home_list}${user_home##*/}\n"
    done <<<"${candidates}"
    home_root=${candidate}
}

tik_migration_current_backup_home() {
    tik_migration_snapshot_home "$1" "$2"
}

tik_migration_backup current
