#!/bin/sh

PREREQ=""

prereqs()
{
	echo "$PREREQ"
}

case $1 in
	prereqs)
		prereqs
		exit 0
	;;
esac

# Modify local lvm.conf (in the initramfs) to lock LVM metadata with:
# global {
# 	metadata_read_only = 1
# }
# activation {
# 	read_only_volume_list = [ "vg0/lv0", "vg0/lv1", "vg1/lv0", "vg1/lv1", "vg1/lv2" ]
# }
# This is done very early in the boot process, before activation of Logical
# Volumes.

# If the system has no Logical Volume registered in fstab, nothing to do:
[ -f "/etc/lvm/bilibop" ] || exit 0

# /proc/cmdline will be parsed several times. We call 'cat' only one time:
readonly CMDLINE="$(cat /proc/cmdline)"

# Set verbosity from boot commandline:
for	param in ${CMDLINE}
do
	case	"${param}" in
		quiet)
			quiet="y"
			break
			;;
	esac
done

# Load functions:
. /scripts/functions
. /usr/lib/bilibop/lockfs.sh

BILIBOP_LOCKFS="true"
BILIBOP_LOCKFS_POLICY="hard"

# Check if BILIBOP_LOCKFS or BILIBOP_LOCKFS_POLICY are overridden from the
# boot commandline. To enable bilibop-lockfs in single-user mode, it is
# necessary to use 'lockfs=force'.
for	param in ${CMDLINE}
do
	case	"${param}" in
		single|S|1)
			single="true"
			;;
		[02-6])
			single="false"
			;;
		nolockfs)
			BILIBOP_LOCKFS="false"
			_force="false"
			;;
		lockfs)
			BILIBOP_LOCKFS="true"
			;;
		lockfs=*)
			BILIBOP_LOCKFS="true"
			for	opt in $(IFS=',' ; echo ${param#lockfs=})
			do
				case	"${opt}" in
					default)
						BILIBOP_LOCKFS_POLICY="hard"
						_force="false"
						;;
					force)
						_force="true"
						;;
					hard|soft)
						BILIBOP_LOCKFS_POLICY="${opt}"
						;;
				esac
			done
			;;
	esac
done

# 'lockfs=force' boot option is available only for single-user sessions:
if	[ "${single}" = "true" ]
then	BILIBOP_LOCKFS="false"
	[ "${_force}" = "true" ] &&
	BILIBOP_LOCKFS="true"
fi

# But it may also happen that a drive is physically locked by a switch (write
# protected). Unfortunately, at this step, there is no way to know if the
# write-protected drive is the one that hosts the system, or not.
if dmesg | grep -q '\([Ww]rite [Pp]rotect [Ii]s [Oo]n\|[MG]i\?B (ro)\)$'; then
	BILIBOP_LOCKFS="true"
	BILIBOP_LOCKFS_POLICY="hard"
fi

# If bilibop-lockfs is disabled, or enabled with a 'soft' policy, do nothing:
if	[ "${BILIBOP_LOCKFS}" = "true" ] &&
	[ "${BILIBOP_LOCKFS_POLICY}" = "hard" ]
then	log_warning_msg "${0##*/}: Set LVM read-only."
else	log_warning_msg "${0##*/}: Nothing to do."
	exit 0
fi

# Now modify 'metadata_read_only' and 'read_only_volume_list'
# variables in (initramfs)/etc/lvm/lvm.conf:
LVM_CONF="/etc/lvm/lvm.conf"
initialize_lvm_conf
set_readonly_lvm_settings

# Also skip root filesystem check
rm -f /sbin/fsck

:
