#!/bin/bash -e
#
# Copyright (c) 2026 SUSE Linux GmbH, Nuernberg, Germany
#
# Remove nested /etc subvolume

# Already there?
if [ -e /etc/fstab ] && [ -z "$(awk '$2 == "/etc" && $3 == "none"' /etc/fstab)" ]; then
	echo "ERROR: No nested subvolume found in /etc/fstab."
	exit 1
fi

if ! mkdir /etc.transactional-update; then
  echo "ERROR: Root file system is not writable - please use transactional-update."
fi

generate_ld_library_path () {
	while read -r line; do
		if [[ $line = "# "* ]]; then
			:
		elif [[ $line = "include "* ]]; then
			generate_ld_library_path < ${line##include } || true
		else
			LD_LIBRARY_PATH="${LD_LIBRARY_PATH}${LD_LIBRARY_PATH:+:}${line}"
		fi
	done
}

# Make sure applications continue to work even without /etc/ld.so.cache
generate_ld_library_path < /etc/ld.so.conf
export LD_LIBRARY_PATH

echo "Removing nested /etc subvolume..."
rsync --quiet --archive --xattrs --acls /etc/ /etc.transactional-update
mv /etc /etc.transactional-update.old
mv /etc.transactional-update /etc
rm -r /etc.transactional-update.old

# Remove entry for /etc
sed -i '/^\/etc \/etc none /d' /etc/fstab

exit 0
