
# Install grubby
#
class grub::grubby {

    case $::operatingsystem {
        "centos","fedora","redhat": {
            package { "grubby":
                ensure => installed,
            }
        }
        default: {
            fail("grub module not supported in ${::operatingsystem}")
        }
    }

}


# Add / remove kernel boot parameters
#
# === Parameters:
#
#   $name:
#       Parameter name to remove/add
#
#   $ensure:
#       Set to present to add parameter and absent to remove it.
#       Defaults to present.
#
# === Sample usage:
#
# grub::kernelparam { "quiet":
#     ensure => absent,
# }
#
# grub::kernelparam { "elevator=noop":
#     ensure => present,
# }
#
define grub::kernelparam($ensure = "present") {

    require grub::grubby

    if $ensure == "present" {
        exec { "grubby --update-kernel=ALL --args=${name}":
            path   => "/bin:/usr/bin:/sbin:/usr/sbin",
            unless => $::operatingsystem ? {
                "fedora" => "egrep '^[[:space:]]*linux[[:space:]].* ${name}( .*)?' /boot/grub2/grub.cfg",
                default  => "grubby --info=`grubby --default-kernel` | egrep '^args=\"(.* )?${name}( .*)?\"'",
            },
            tag    => "bootstrap",
        }
    } elsif $ensure == "absent" {
        exec { "grubby --update-kernel=ALL --remove-args=${name}":
            path   => "/bin:/usr/bin:/sbin:/usr/sbin",
            onlyif => $::operatingsystem ? {
                "fedora" => "egrep '^[[:space:]]*linux[[:space:]].* ${name}( .*)?' /boot/grub2/grub.cfg",
                default  => "grubby --info=`grubby --default-kernel` | egrep '^args=\"(.* )?${name}( .*)?\"'",
            },
            tag    => "bootstrap",
        }
    } else {
        fail("invalid value '${ensure}' for parameter 'ensure'")
    }

}


# Set grub password
#
# === Parameters:
#
#   $password:
#       SHA-512 hash of password to set for grub.
#
class grub::password($password) {

    case $::operatingsystem {
        "centos","redhat": {
            # add password if not exist
            augeas { "set-grub-password":
                context => "/files/boot/grub/menu.lst",
                changes => [
                  "ins password after default",
                  "clear password/encrypted",
                  "set password '${password}'",
                ],
                onlyif  => "match password size == 0",
            }
            # change password
            augeas { "change-grub-password":
                context => "/files/boot/grub/menu.lst",
                changes => "set password '${password}'",
                require => Augeas["set-grub-password"],
            }
        }
        default: {
            fail("grub::password not supported on ${::operatingsystem}")
        }
    }

}
