#!/usr/bin/env bash

if [[ ! $1 ]]; then
	cat <<-END
		Usage: ${0##*/} enable|disable|status

		Enable or disable read-only on currently booted Btrfs subvolume.
	END
	exit 0
fi

if [[ $EUID -ne 0 ]]; then
	printf 'You have to be root to perform this action.\n'
	exit 1
fi

if [[ $2 ]]; then
	printf 'This script only takes a single argument.\n'
	exit 1
fi

if [[ $1 == 'enable' ]]; then

	if btrfs property get / 2> /dev/null | grep -q 'ro=true'; then
		printf 'The root filesystem is already locked.\n'
		exit 0
	fi

	printf 'Locking the root filesystem...\n'
	btrfs property set / ro true

elif [[ $1 == 'disable' ]]; then

	if btrfs property get / 2> /dev/null | grep -q 'ro=false'; then
		printf 'The root filesystem is already unlocked.\n'
		exit 0
	fi

	printf 'Unlocking the root filesystem...\n'
	btrfs property set / ro false &&
		printf 'The root filesystem has now been unlocked, note that any changes made to it will not be carried over to future OS image updates.\n'

elif [[ $1 == 'status' ]]; then

	if btrfs property get / 2> /dev/null | grep -q 'ro=true'; then
		printf 'enabled\n'
	elif btrfs property get / 2> /dev/null | grep -q 'ro=false'; then
		printf 'disabled\n'
	else
		printf 'unknown\n'
		exit 1
	fi

else
	printf 'No valid argument provided.\n'
	exit 1
fi
