#!/bin/bash
#
# Copyright (C) 2015-2016 Red Hat, Inc.
#
# This file is part of atomic-devmode.
#
# atomic-devmode is free software: you can redistribute it
# and/or modify it under the terms of the GNU Lesser General
# Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# atomic-devmode is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU Lesser General Public License for
# more details.
#
# You should have received a copy of the GNU Lesser General
# Public License along with atomic-devmode. If not, see
# <http://www.gnu.org/licenses/>.

set -euo pipefail
IFS=$'\n\t'

LIBEXEC="/usr/libexec/atomic-devmode"
GRUB="/etc/grub.d"

main() {

	if [ $# -ne 1 ] || { [[ $1 != "add" ]] && \
	                     [[ $1 != "remove" ]]; }; then
		echo "Usage: $0 <add|remove>" >&2
		exit 1
	fi

	if [[ $1 == add ]]; then
		ln -sf "$LIBEXEC/grub2_hook" "$GRUB/10_devmode+"
		ln -sf "$LIBEXEC/grub2_hook" "$GRUB/99_devmode-"
	else # remove
		rm -f "$GRUB/10_devmode+"
		rm -f "$GRUB/99_devmode-"
	fi

	# Generate a new grub config. NB: We manually override the bootversion for
	# now because ostree versions before v2016.1 failed to detect the version
	# properly (see https://github.com/GNOME/ostree/pull/165). We can probably
	# drop this patch later on.
	local bootver
	bootver=$(readlink /boot/loader)
	_OSTREE_GRUB2_BOOTVERSION=${bootver#*.} \
	        grub2-mkconfig -o /boot/loader/grub.cfg
}

main "$@"
