#!/bin/sh

. /etc/control.d/functions

FACILITY_NAME=symlinks
CONFIG=/etc/sysctl.d/90-override.conf

new_summary "$FACILITY_NAME protection on shared partitions"

new_help enabled "Enable $FACILITY_NAME protection"
new_help disabled "Disable $FACILITY_NAME protection"


read_protection() {
	local value=

	value="$(grep -sE -- "^fs\.protected_$FACILITY_NAME" \
		"${CONFIG%/*}"/*.conf 2>/dev/null |sort |
		tail -n1 |cut -f2 -d= |sed -E 's,^\s*,,')"
	if [ -z "$value" ]; then
		value="$(sysctl "fs.protected_$FACILITY_NAME" \
			2>/dev/null |awk '{print $3;}')"
	fi
	if [ -z "$value" ]; then
		echo "undefined"
	elif [ "$value" = "1" ]; then
		echo "enabled"
	else
		echo "disabled"
	fi
}

write_protection() {
	local err= oldval= newval="$1"
	local regex="^fs\.protected_$FACILITY_NAME"

	if [ ! -d "${CONFIG%/*}" ]; then
		mkdir -m755 -- "${CONFIG%/*}" || err=1
	fi
	if [ ! -f "$CONFIG" ]; then
		touch -- "$CONFIG" || err=1
	else
		oldval="$(grep -sE -- "$regex" "$CONFIG" 2>/dev/null |
			sort |tail -n1 |cut -f2 -d= |sed -E 's,^\s*,,')"
	fi
	if [ "$oldval" != "$newval" -a -n "$oldval" ]; then
		sed -i -E -- "s,^($regex).*$,\1 = $newval,g" "$CONFIG" || err=1
	elif [ "$oldval" != "$newval" -a -z "$oldval" ]; then
		echo "fs.protected_$FACILITY_NAME = $newval" >> "$CONFIG" || err=1
	fi
	sysctl -w "fs.protected_$FACILITY_NAME=$newval" || err=1
	[ -z "$err" ] || exit 1
}

control_fsprot() {
	local REQUEST="$*"

	case "$REQUEST" in
	help|'help '*)
		control_help "${REQUEST#help}"
		;;
	list)	control_list
		;;
	summary)
		control_summary
		;;
	status|'')
		read_protection
		;;
	enabled)
		write_protection 1
		;;
	disabled)
		write_protection 0
		;;
	*)	exit 1
		;;
	esac
}

control_fsprot "$*"
