# 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_legacy_discover() {
    local candidate candidates user_home parent_is_btrfs is_subvolume
    # Shared-home layouts include Aeon/openSUSE @home and @/home, including
    # homes mounted separately through the source system's fstab.
    for candidate in "${TIK_ROOT_MNT}/home" \
        "${TIK_SOURCE_BTRFS_TOP:-${TIK_ROOT_MNT}}/@home" \
        "${TIK_SOURCE_BTRFS_TOP:-${TIK_ROOT_MNT}}/@/home"; do
        [[ -d ${candidate} && ! -L ${candidate} ]] || continue
        candidates="$(prun /usr/bin/find "${candidate}" -mindepth 1 -maxdepth 1 \
            -type d ! -name '.*' -print)" || error "Cannot list source home directories."
        [[ -n ${candidates} ]] || continue
        home_root=${candidate}
        break
    done
    [[ -n ${home_root} ]] || return 0
    parent_is_btrfs=0
    [[ $(findmnt --first-only --direction backward -nro FSTYPE --target "${home_root}") != btrfs ]] || parent_is_btrfs=1
    while IFS= read -r user_home; do
        prun-opt /usr/sbin/btrfs subvolume show "${user_home}" >/dev/null 2>&1
        is_subvolume=0
        [[ ${retval} != 0 ]] || is_subvolume=1
        [[ ${is_subvolume} == 1 || ${parent_is_btrfs} == 1 ]] || continue
        home_subvolumes+=("${user_home}")
        home_is_subvolume+=("${is_subvolume}")
        home_names+=("${user_home##*/}")
        home_list="${home_list}${user_home##*/}\n"
    done <<<"${candidates}"
}

tik_migration_legacy_backup_home() {
    local user_home=$1 snapshot=$2 username=$3 index=$4 backup
    if [[ ${home_is_subvolume[${index}]} == 1 ]]; then
        tik_migration_snapshot_home "${user_home}" "${snapshot}"
    else
        # Ordinary directories in shared @home cannot be snapshotted alone.
        # Preserve their metadata in the same per-user backup format used by
        # current systems, so account and home restoration remains shared.
        backup="${homes_dir}/${snapshot_prefix}${username}"
        log "[mig] copying ordinary home directory ${user_home}"
        prun /usr/sbin/btrfs subvolume create "${backup}"
        prun /usr/bin/cp -a --reflink=auto "${user_home}/." "${backup}/"
        prun /usr/sbin/btrfs property set -f -ts "${backup}" ro true
    fi
}

tik_migration_backup legacy
