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

# NOTE: this runs outside the chroot!
# Mangle subvol setup from calamares to systemd conforming lineup.

set -ex

ROOT=$1
[ "$ROOT" = "" ] && exit 1

device=$(findmnt --noheadings --nofsroot --output SOURCE "$ROOT")
[ "$device" = "" ] && exit 1

. /etc/os-release

tmpdir=$(mktemp --directory)

# Calamares likes to mount stuff even with an empty config. Throw it away again.
cd "$ROOT"
umount -R ./*
rm -rfv ./*
btrfs subvolume sync . || true
umount -R --lazy "$ROOT" # unmount is important as otherwise we still hold a subvolume open and it can never sync deletion

mount -o ro /dev/gpt-auto-root /system
mount -o rw "$device" "$tmpdir"
cd "$tmpdir"
rm -rfv ./*
btrfs subvolume sync . || true

btrfs quota enable --simple .
btrfs send --compressed-data "/system/@kde-linux_$IMAGE_VERSION" | btrfs receive .
btrfs subvolume create @home
btrfs subvolume create @root
btrfs subvolume create @locale
btrfs subvolume create @snap
btrfs subvolume create @var-overlay
btrfs subvolume create @etc-overlay
mkdir @var-overlay/upper @var-overlay/work @etc-overlay/upper @etc-overlay/work

# Overmount calamares' mount with the subvol mount
mount -o "subvol=@kde-linux_$IMAGE_VERSION" "$device" "$ROOT"
mount -t proc proc "$ROOT/proc"
mount -t sysfs sys "$ROOT/sys"
mount -o bind /dev "$ROOT/dev"
mount -t tmpfs tmpfs "$ROOT/run"
mkdir "$ROOT/run/udev"
mount -o bind /run/udev "$ROOT/run/udev"
mount -t efivarfs efivarfs "$ROOT/sys/firmware/efi/efivars"
_kde-linux-overlay "$device" "$ROOT"

# ESP is a bit tricky. Find the block device of the root partition and then we'll ask systemd for an ESP on that device.
# ... and luks devices are even more tricky because we need to get the real device first
realdevice=$(realpath --relative-to /dev "$device")
if [ -r "/sys/block/$realdevice/dm/" ]; then
    for slave in /sys/block/"$realdevice"/slaves/*; do
        realdevice=$(basename "$slave")
        break
    done
fi
blockdev=/dev/$(basename "$(readlink --canonicalize "/sys/class/block/$realdevice/..")")
espdev=$(_kde-linux-find-esp "$blockdev")
mount "$espdev" "$ROOT/boot"

# Once everything is in place we'll shove some extra data into the overlays.
# We notably don't want to carry flatpaks in the rootfs but for purposes of the image file they must be shipped somehow.
# In the live session they are mounted in place, for the installed system we actually seed /var/lib/flatpak with data.
# TODO: doing it this way means we can't factory reset flatpaks. Figure out what to do about that.
rm -rf "$ROOT/var/lib/flatpak"
cp -ra /system/@flatpak "$ROOT/var/lib/flatpak"
