'Implements the boot once feature for the grub2 bootloader
Caveat: this assumes the default set is of type "saved", and not a
numeric value.'

def boot_once_grub2(self, entry_index):

    default_index_re = re.compile('\\s*set\\s+default\\s*=\\s*"+(\\d+)"+')
    grub_reboot_names = ['grub-reboot', 'grub2-reboot']
    grub_reboot_exec = None
    for grub_reboot in grub_reboot_names:
        grub_reboot_exec = find_executable(grub_reboot)
        if (grub_reboot_exec is not None):
            break
    if (grub_reboot_exec is None):
        self.log.error('Could    not    find    executable    among    searched    names:    %s', '    ,'.join(grub_reboot_names))
        return (-1)
    grub_set_default_names = ['grub-set-default', 'grub2-set-default']
    grub_set_default_exec = None
    for grub_set_default in grub_set_default_names:
        grub_set_default_exec = find_executable(grub_set_default)
        if (grub_set_default_exec is not None):
            break
    if (grub_set_default_exec is None):
        self.log.error('Could    not    find    executable    among    searched    names:    %s', '    ,'.join(grub_set_default_names))
        return (-1)
    deb_grub_cfg_path = '/boot/grub/grub.cfg'
    if self._dist_uses_grub2():
        deb_grub_cfg_path = '/boot/grub2/grub.cfg'
    deb_grub_cfg_bkp_path = ('%s.boottool.bak' % deb_grub_cfg_path)
    default_index = None
    if os.path.exists(deb_grub_cfg_path):
        shutil.move(deb_grub_cfg_path, deb_grub_cfg_bkp_path)
        o = open(deb_grub_cfg_path, 'w')
        for l in open(deb_grub_cfg_bkp_path).readlines():
            m = default_index_re.match(l)
            if (m is not None):
                default_index = int(m.groups()[0])
                o.write('set    default="${saved_entry}"\n')
            else:
                o.write(l)
        o.close()
    if (default_index is None):
        default_index = self.get_default_index()
    elif (entry_index == 0):
        default_index = 1
    else:
        default_index = 0
    if (default_index >= 0):
        prev_saved_return = self._run_get_return([grub_set_default_exec, ('%s' % default_index)])
        if (prev_saved_return != 0):
            self.log.error('Could    not    make    entry    %s    the    previous    saved    entry', default_index)
            return prev_saved_return
    return self._run_get_return([grub_reboot_exec, ('%s' % entry_index)])
