#!/bin/bash

# This script sets the password associated with the root account.  The same
# password is also used to protect GRUB.

# Override grub config in the the case of grub2
# This will sort of work but the update will be lost
# if update-grub is run, have filed a PR to get this fixed 1479535
GRUBCONF="/boot/grub2/grub.cfg"
read -r rootpasswd

STATUS=0

echo "Setting root password."
echo "root:$rootpasswd" | /usr/sbin/chpasswd
if [ $? -ne 0 ]; then
    STATUS=$?
    echo "ERROR: Unable to set root password."
fi

echo "Setting grub password."
hash=`echo "$rootpasswd" | /usr/bin/openssl passwd -1 -stdin`
if [ $? -ne 0 ]; then
    STATUS=$?
    echo "ERROR: Unable to set grub password (hashing failed)."
else
    pwline="password --md5 $hash"
    if ! /usr/bin/grep password $GRUBCONF > /dev/null ; then
        /usr/bin/sed -i "/^timeout/a $pwline" $GRUBCONF
    else
        /usr/bin/sed -i "/^password/c $pwline" $GRUBCONF
    fi
    if [ $? -ne 0 ]; then
        STATUS=$?
        echo "ERROR: Unable to set grub password."
    fi
fi

exit $STATUS
