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

set -eux

if ! grep "kde-linux.live=1" /proc/cmdline; then
    echo "kde-linux.live=1 not in cmdline"
    exit 1
fi

if [ "$(readlink --canonicalize /dev/disk/by-partlabel/KDELinuxLive)" != "$(readlink --canonicalize /dev/gpt-auto-root)" ]; then
    echo "gpt-auto-root is not KDELinuxLive"
    exit 1
fi

# Replicate what systemd-volatile-root does. Unfortunately we can't just use the volatile root because you can't
# overlay with an overlay. This means we potentially claim a lot of RAM (25% for root + 15% for flatpaks).
# Not ideal but there's no way I can see to get access to the volatile-sysroot (it gets unmounted and removed
# before systemd-volatile-root exits).

mkdir --mode 0700 /run/kde-linux/
mkdir --mode 0700 /run/kde-linux/overlay-var-lib-flatpak
mount -t tmpfs tmpfs /run/kde-linux/overlay-var-lib-flatpak -o mode=0755,size=15%,nr_inodes=1m
mkdir --mode 0755 /run/kde-linux/overlay-var-lib-flatpak/upper
mkdir --mode 0755 /run/kde-linux/overlay-var-lib-flatpak/work

mount -t overlay overlay /var/lib/flatpak \
    -o lowerdir=/var/lib/flatpak,upperdir=/run/kde-linux/overlay-var-lib-flatpak/upper,workdir=/run/kde-linux/overlay-var-lib-flatpak/work
