#!/bin/bash

# Copyright (C) 2026 Matthias Luescher
#
# Authors:
#  Matthias Luescher
#
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with the edi project configuration.  If not, see <http://www.gnu.org/licenses/>.

# ----------------------------------------------------------------------------
# Small helper script that makes sure that we are booting from a writeable
# btrfs subvolume.
# ----------------------------------------------------------------------------

set -o nounset
set -o errexit
set -o pipefail

if [[ $EUID -ne 0 ]] ; then
   >&2 echo "Error: Use root user to execute this script."
   exit 1
fi

CURRENT_ROOT_DEVICE=$(mount | sed -n 's|^\(/dev/.*\) on / .*|\1|p')
if [ -z "${CURRENT_ROOT_DEVICE}" ] ; then
    >&2 echo "Error: Unable to identify the current root device."
   exit 1
fi

ROOTFS_TYPE="$(blkid -o value -s TYPE "${CURRENT_ROOT_DEVICE}")"
if [ "${ROOTFS_TYPE}" != "btrfs" ] ; then
    echo "No snapshot needed, root ${CURRENT_ROOT_DEVICE} is of type ${ROOTFS_TYPE}."
    exit 0
fi

SNAPSHOT_RO="$(btrfs property get -t subvol / | awk -F'=' '/^ro=/ {print $2}')"
if [ "${SNAPSHOT_RO}" == "false" ] ; then
    echo "No snapshot needed, root ${CURRENT_ROOT_DEVICE} is already writable."
    exit 0
else
    DEFAULT_SUBVOLUME="$(btrfs subvolume get-default /)"
    DEFAULT_SUBVOLUME="${DEFAULT_SUBVOLUME##* }"
    CURRENT_SUBVOLUME="$(btrfs subvolume show / | head -n 1)"
    ROOT_MOUNT="/mnt"
    RW_SNAPSHOT="@"

    if [ "${CURRENT_SUBVOLUME}" == "${RW_SNAPSHOT}" ] ; then
        >&2 echo "Error: Current subvolume ${CURRENT_SUBVOLUME} conflicts with target snapshot ${RW_SNAPSHOT}."
        exit 1
    fi

    if [ "${CURRENT_SUBVOLUME}" != "${DEFAULT_SUBVOLUME}" ] ; then
        >&2 echo "Error: Current subvolume ${CURRENT_SUBVOLUME} does not match default subvolume ${DEFAULT_SUBVOLUME}."
        exit 1
    fi

    echo "Snapshot needed, root ${CURRENT_ROOT_DEVICE}: ${DEFAULT_SUBVOLUME} --> ${RW_SNAPSHOT}."
    mount -t btrfs -o subvolid=5 "${CURRENT_ROOT_DEVICE}" "${ROOT_MOUNT}"
    if [ -e "${ROOT_MOUNT}"/"${RW_SNAPSHOT}" ] ; then
        btrfs subvolume delete --commit-after "${ROOT_MOUNT}"/"${RW_SNAPSHOT}"
    fi
    btrfs subvolume snapshot "${ROOT_MOUNT}"/"${DEFAULT_SUBVOLUME}" "${ROOT_MOUNT}"/"${RW_SNAPSHOT}"
    btrfs subvolume set-default "${ROOT_MOUNT}"/"${RW_SNAPSHOT}"

    echo "Rebooting system to apply writable subvolume..."
    /usr/bin/systemctl reboot --no-block
fi

