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

set -ex

rootdisk=/dev/disk/by-partlabel/KDEOS
if [ -b /dev/gpt-auto-root ]; then
    # When the partition was auto detected we can just use the auto-root device
    rootdisk=/dev/gpt-auto-root
fi
rootdisk=${1:-$rootdisk}
sysroot=${2:-/sysroot}

# TODO should probably transition to .mount units or a generator instead
# NOTE: this is also called by calamares, so maybe mount units are a bad idea

if [ -d "${sysroot}/system/@etc-overlay" ]; then
    # already mounted
    exit 0
fi

mount -v \
    -o rw,subvol=/ \
    "$rootdisk" "${sysroot}/system"

# Make sure our subvolumes exist! In particular if we introduce subvolumes after installation.
# FIXME This is a bit garbage. It'd be much tidier if we could tell repart to do this for us. But in some sort of
# safe mode so it doesn't twiddle the partition table.
# FIXME does this even work? do we have btrfs util in the initrd?

[ -d "${sysroot}/system/@root" ] || btrfs subvolume create "${sysroot}/system/@root"

mount -v \
    -o rw,subvol=@home \
    "$rootdisk" "${sysroot}/home"
mount -v \
    -o rw,subvol=@root \
    "$rootdisk" "${sysroot}/root"
mount -v \
    -o rw,subvol=@snap \
    "$rootdisk" "${sysroot}/snap"
mount -v \
    -o rw,subvol=@locale \
    "$rootdisk" "${sysroot}/usr/lib/locale"
mount -v \
    -t overlay \
    -o "rw,lowerdir=${sysroot}/etc,upperdir=${sysroot}/system/@etc-overlay/upper,workdir=${sysroot}/system/@etc-overlay/work,index=off,metacopy=off" \
    overlay "${sysroot}/etc"
mount -v \
    -t overlay \
    -o "rw,lowerdir=${sysroot}/var,upperdir=${sysroot}/system/@var-overlay/upper,workdir=${sysroot}/system/@var-overlay/work,index=off,metacopy=off" \
    overlay "${sysroot}/var"

# TODO: should we maybe also mount /etc into the initrd /etc so we have early access to fstab and the like
