#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2025 Harald Sitter <sitter@kde.org>

set -eux

. /etc/os-release

if [ -b /dev/gpt-auto-root ]; then
    echo "gpt-auto-root exists"
else
    echo "gpt-auto-root does not exist"
    exit 1
fi

if [ -d /run/kde-linux-rootfs-transition ]; then
    echo "/run/kde-linux-rootfs-transition exists"
    exit 0
fi

mkdir /run/kde-linux-rootfs-transition
mount -o rw,subvol=/ /dev/gpt-auto-root /run/kde-linux-rootfs-transition

# NOTE: this is required to be here!
# It's a bit awkward but the system drive is not mounted yet, so we can only peek into it through our mount.
# This is effectively the no-op condition that should be in the unit but can't be because we need the mount.
# In a way we could think about moving the mounts into a generator TBH. Then we can do proper condition management on
# the systemd side. Question is if they get correctly unmounted automatically.
if [ -e /run/kde-linux-rootfs-transition/@system ]; then
    echo "@system exists"
    cd /
    umount --recursive --lazy /run/kde-linux-rootfs-transition
    exit 0
fi

# We need access to our usr so we can import the /usr/share/factory/var.
# Previously this was an overlay so we don't really know which files were used from the lower dir.
mkdir /run/kde-linux-rootfs-transition-usr
mount -o ro,X-mount.subdir=usr "/run/kde-linux-rootfs-transition/kde-linux_$IMAGE_VERSION.erofs" /run/kde-linux-rootfs-transition-usr

_kde-linux-btrfs-migrator /run/kde-linux-rootfs-transition /run/kde-linux-rootfs-transition-usr

cd /
umount --recursive --lazy /run/kde-linux-rootfs-transition-usr
umount --recursive --lazy /run/kde-linux-rootfs-transition
