#!/bin/sh
#Copyright: 2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: oneshot; invoke with: sv once umountroot

exec 2>&1

ebegin() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
eend() { r=${1:-0}; shift || true; [ "$r" -eq 0 ] || [ "${VERBOSE:-}" = no ] || echo "$*" >&2; return "$r"; }
einfo() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
ewarn() { echo "$@" >&2; }
eerror() { echo "$@" >&2; }

. /lib/init/vars.sh

persist_rc_log() {
	local runlog="${RC_SVCDIR:-/run/openrc}/rc.log"
	[ -f "$runlog" ] || runlog=/run/openrc/rc.log
	if [ -f "$runlog" ] && [ -d /var/log ]; then
		cat "$runlog" >> /var/log/rc.log 2>/dev/null || true
	fi
}

remount_ro() {
	local label="$1" mp="$2" ES=0
	local MOUNT_FORCE_OPT=
	[ "$(uname -s)" = "GNU/kFreeBSD" ] && MOUNT_FORCE_OPT=-f

	if [ "$VERBOSE" != no ]; then
		ebegin "Mounting $label filesystem read-only"
	fi

	mount $MOUNT_FORCE_OPT -n -o remount,ro -t dummytype dummydev "$mp" 2>/dev/null \
	|| mount $MOUNT_FORCE_OPT -n -o remount,ro              dummydev "$mp" 2>/dev/null \
	|| mount $MOUNT_FORCE_OPT -n -o remount,ro                       "$mp" 2>/dev/null
	ES=$?

	if [ "$VERBOSE" != no ]; then
		if [ "$ES" -ne 0 ]; then
			ewarn "Could not remount $mp read-only; continuing shutdown"
		fi
		eend 0
	fi
	return 0
}

sync
persist_rc_log
sync
remount_ro root /
if mountpoint -q /usr; then
	remount_ro /usr /usr
fi
exit 0
