#!/bin/bash
#############################################################################
#
# Copyright Avaya Inc., All Rights Reserved.
#
# THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Avaya Inc.
#
# The copyright notice above does not evidence any actual or intended
# publication of such source code.
#
# Some third-party source code components may have  been modified from their
# original versions by Avaya Inc.
#
# The modifications are Copyright Avaya Inc., All Rights Reserved.
#
# Avaya - Confidential & Restricted. May not be distributed further without
# written permission of the Avaya owner.
#
#############################################################################
# Wrapper script to the grub2-setpassword command.  By wrapping the script
# the sudo command can be automatically used and information can be
# logged.
#
# Usage:
# 	-p <password>:  The password from grub2-mkpasswd-pbkdf2 can be passed in.
#
# To allow this command to be used by a user other than root then a similar
# entry in sudoers file is needed:
#
# <User or Group> ALL=(root) PASSWD: /opt/avaya/common_os/bin/setBootPassword.sh
# 

# Must be executed as root
[ $UID -eq 0 ] || exec sudo $0 "$@"	

if [ ! -x /sbin/grub2-setpassword ]
then
	echo "Unable to set boot password. Is grub2 the configured boot loader?"
	exit 1
fi

while getopts "p:" CMD_OPTION
do
	case "${CMD_OPTION}" in
		p) GRUB2_PASSWORD=${OPTARG};;
	esac
done

if [ -z "$GRUB2_PASSWORD" ]
then
	# collect the password
	# use a temp file to clean up the output to the user
	TMP=$(mktemp)
	/sbin/grub2-setpassword 2>$TMP
	if [ $? != 0 ]
	then
		# stip off the extra output and just print the error message
		logger -p auth.err "Failed to set boot loader password." 
		head -1 $TMP | sed 's/.*://'
		exit 2
	else
		logger -p auth.info "Successful set boot loader password."
	fi
else
	# password was passed in
	# make sure it is in the correct format
	echo "$GRUB2_PASSWORD" | egrep "grub\.pbkdf2\.sha512\..{5}\..{128}\..{128}$"
	if [ $? != 0 ]
	then
		echo "Password must be in the format generated by grub2-mkpasswd-pbkdf2"
		exit 3
	fi

	echo "GRUB2_PASSWORD=$GRUB2_PASSWORD" > /boot/grub2/user.cfg
fi
rm -f $TMP

grub2-mkconfig -o /boot/grub2/grub.cfg
