#!/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

# Correct the GPT partition type if necessary (e.g., from manual partitioning)
# This ensures /dev/gpt-auto-root is available for systemd detection
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/..")")

# Extract partition number from device path
partnum=$(echo "$device" | sed -n 's/.*[^0-9]\([0-9]\+\)$/\1/p')

arch=$(uname -m)
case "$arch" in
    x86_64)
        root_guid="4f68bce3-e8cd-4db1-96e7-fbcaf984b709"
        ;;
    i686|i386)
        root_guid="44479540-f297-41b2-9af7-d131d5f0458a"
        ;;
    aarch64)
        root_guid="b921b045-1df0-41c3-af44-4c6f280d3fae"
        ;;
    armv7l|armv7h)
        root_guid="69dad710-2ce4-4e3c-b16c-21a1d49abed3"
        ;;
    riscv64)
        root_guid="72ec70a6-cf74-40e6-bd49-4bda08e8f224"
        ;;
    loongarch64)
        root_guid="77055800-792c-4f94-b39a-98c91b762bb6"
        ;;
    *)
        echo "Unknown architecture: $arch, skipping partition type correction"
        root_guid=""
        ;;
esac

if [ -n "$partnum" ] && command -v sfdisk >/dev/null 2>&1; then
    # Check current partition type and correct if needed
    # 4f68bce3-e8cd-4db1-96e7-fbcaf984b709 is Linux root (x86-64)
    current_guid=$(sfdisk --part-type "$blockdev" "$partnum" 2>/dev/null || echo "")
    echo "current_guid: $current_guid"
    echo "root_guid: $root_guid"
    if [ -n "$current_guid" ] && [ "$current_guid" != "$root_guid" ]; then
        echo "Correcting partition type from $current_guid to Linux root (x86-64)"
        sfdisk --part-type "$blockdev" "$partnum" "$root_guid" || true
        # Reload partition table
        partprobe "$blockdev" 2>/dev/null || true
        # Give udev a moment to update /dev/gpt-auto-root
        sleep 1
    fi
fi


. /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 subvolume create @system
btrfs subvolume create @system/etc
mkdir @system/boot @system/proc @system/sys @system/dev @system/run @system/usr
cp /dev/gpt-auto-root kde-linux_$IMAGE_VERSION.erofs

# Overmount calamares' mount with the subvol mount
mount -o "subvol=@system" "$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" # This is not part of @system but rather the $ROOT (do not move this to the mkdir list of @system!)
mount -o bind /run/udev "$ROOT/run/udev"
mount -t efivarfs efivarfs "$ROOT/sys/firmware/efi/efivars"
mount -o ro,X-mount.subdir=usr /dev/gpt-auto-root "$ROOT/usr"

# 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=$(/usr/lib/find-esp "$blockdev")
mount "$espdev" "$ROOT/boot"

# Bit of a crutch to get systemd's base_filesystem_create() to run so the / gets populated with symlinks.
# Exit code is not indicative of to the function having run - ignore it.
systemd-nspawn -D "$ROOT" "true" || true

# Apply the factory
/usr/lib/etc-factory --sysroot "$ROOT/" --replace --migrate

# Initialize systemd stuff
systemd-sysusers --root="$ROOT"

# Add a marker file to indicate this install included plasma-setup.
# This ensures plasma-setup won't run for existing installations.
install -d -m 0755 "$ROOT/var/lib/kde-linux"
install -m 0644 /dev/null "$ROOT/var/lib/kde-linux/installed-with-plasma-setup"

# Make sure presets are applied
systemctl --root="$ROOT" preset-all
systemctl --root="$ROOT" preset-all --global

# tmpfiles are final and should come at last
# exclude /usr because some tmpfiles are rubbish and assume /usr is writable...
systemd-tmpfiles --root="$ROOT" --exclude-prefix=/usr --create
