#!/usr/bin/env bash

# Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#
# Enables FIPS on Mariner 2.0
#

set -euo pipefail

echo "Installing packages required packages to enable FIPS..."
sudo tdnf install -y grubby dracut-fips

#
# Set boot_uuid variable for the boot partition if different from the root
#
boot_dev="$(df /boot/ | tail -1 | cut -d' ' -f1)"
echo "Boot partition: $boot_dev"

root_dev="$(df / | tail -1 | cut -d' ' -f1)"
echo "Root partition: $root_dev"

boot_uuid=""
if [ "$boot_dev" != "$root_dev" ]; then
    boot_uuid="boot=UUID=$(blkid $boot_dev -s UUID -o value)"
    echo "Boot UUID: $boot_uuid"
fi

#
# Enable FIPS and set boot= parameter
#
echo "Enabling FIPS..."
if sudo grub2-editenv - list | grep -q kernelopts; then
    set -x
    sudo grub2-editenv - set "$(sudo grub2-editenv - list | grep kernelopts) fips=1 $boot_uuid"
else
    set -x
    sudo grubby --update-kernel=ALL --args="fips=1 $boot_uuid"
fi