#!/usr/sbin/openrc-run

description="Mount the root and /usr filesystems read-only"

depend()
{
	# Stop after local umount/crypto/clock (bootlogd optional).
	before cryptdisks-early cryptdisks umountfs fake-hwclock
}

stop()
{
	. /lib/init/vars.sh

	# Persist OpenRC log from tmpfs onto / before remounting read-only.
	persist_rc_log() {
		local runlog="${RC_SVCDIR:-/run/openrc}/rc.log"
		# Common custom path when rc_log_path points at tmpfs.
		[ -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

		# Always silence mount(8): a busy / is expected while OpenRC still
		# holds its log fd, and the message otherwise looks like a hard fault.
		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
	return 0
}

start()
{
	:
}
