# platform = Red Hat Enterprise Linux 8
# reboot = true
# strategy = configure
# complexity = medium
# disruption = low

- name: "Ensure BLS boot entries options contain {{{ ARG_NAME }}}={{{ ARG_VALUE }}}"
  block:
    - name: "Check how many boot entries exist "
      find:
        paths: "/boot/loader/entries/"
        patterns: "*.conf"
      register: n_entries

    - name: "Check how many boot entries set {{{ ARG_NAME }}}={{{ ARG_VALUE }}}"
      find:
        paths: "/boot/loader/entries/"
        contains: "^options .*{{{ ARG_NAME }}}={{{ ARG_VALUE }}}.*$"
        patterns: "*.conf"
      register: n_entries_options

    - name: "Update boot entries options"
      command: grubby --update-kernel=ALL --args="{{{ ARG_NAME }}}={{{ ARG_VALUE }}}"
      when: n_entries is defined and n_entries_options is defined and n_entries.matched != n_entries_options.matched

    - name: "Check if /etc/kernel/cmdline exists"
      stat:
        path: /etc/kernel/cmdline
      register: cmdline_stat

    - name: "Check if /etc/kernel/cmdline contains {{{ ARG_NAME }}}={{{ ARG_VALUE }}}"
      find:
        paths: "/etc/kernel/"
        patterns: "cmdline"
        contains: "^.*{{{ ARG_NAME }}}={{{ ARG_VALUE }}}.*$"
      register: cmdline_find

    - name: "Add /etc/kernel/cmdline contains {{{ ARG_NAME }}}={{{ ARG_VALUE }}}"
      lineinfile:
        create: yes
        path: "/etc/kernel/cmdline"
        line: '{{{ ARG_NAME }}}={{{ ARG_VALUE }}}'
      when: cmdline_stat is defined and not cmdline_stat.stat.exists

    - name: "Append /etc/kernel/cmdline contains {{{ ARG_NAME }}}={{{ ARG_VALUE }}}"
      lineinfile:
        path: "/etc/kernel/cmdline"
        backrefs: yes
        regexp: "^(.*)$"
        line: '\1 {{{ ARG_NAME }}}={{{ ARG_VALUE }}}'
      when: cmdline_stat is defined and cmdline_stat.stat.exists and cmdline_find is defined and cmdline_find.matched == 0

