---
- name: Check if GRUB_CMDLINE_LINUX line exists in /etc/default/grub
  tags: [packages, nvidia]
  ansible.builtin.command:
    cmd: grep -E '^GRUB_CMDLINE_LINUX=' /etc/default/grub
  register: nymph_grub_cmdline_check
  changed_when: false
  failed_when: false

- name: Initialize empty GRUB_CMDLINE_LINUX line if missing
  tags: [packages, nvidia]
  ansible.builtin.lineinfile:
    path: /etc/default/grub
    line: 'GRUB_CMDLINE_LINUX=""'
    insertafter: '^GRUB_CMDLINE_LINUX_DEFAULT='
    state: present
  when: nymph_grub_cmdline_check.rc != 0
  register: nymph_grub_cmdline_init

- name: Append NVIDIA kernel parameters to GRUB_CMDLINE_LINUX if missing
  tags: [packages, nvidia]
  ansible.builtin.replace:
    path: /etc/default/grub
    regexp: '^(GRUB_CMDLINE_LINUX="(?:(?!{{ item | regex_escape }})[^"])*?)"$'
    replace: '\1 {{ item }}"'
  loop:
    - nouveau.modeset=0
    - nvidia-drm.modeset=1
  register: nymph_grub_cmdline_append

- name: Regenerate GRUB configuration
  tags: [packages, nvidia]
  ansible.builtin.command: grub-mkconfig -o /boot/grub/grub.cfg
  changed_when: true
  when: nymph_grub_cmdline_init is changed or nymph_grub_cmdline_append is changed

- name: Configure NVIDIA power management for hybrid graphics
  tags: [packages, nvidia]
  ansible.builtin.copy:
    dest: /etc/modprobe.d/nvidia-power-management.conf
    content: |
      options nvidia "NVreg_DynamicPowerManagement=0x02"
    owner: root
    group: root
    mode: "0644"

- name: Install prime-run wrapper script for NVIDIA PRIME offload
  tags: [nvidia, dotfiles, dotfiles:host]
  ansible.builtin.copy:
    src: "{{ playbook_dir }}/../dotfiles/nymph/.local/bin/prime-run"
    dest: "{{ user_home }}/.local/bin/prime-run"
    owner: "{{ username }}"
    group: "{{ user_group }}"
    mode: "0755"
    force: false

- name: Wrap alacritty with prime-run for NVIDIA PRIME offload
  tags: [nvidia, dotfiles, dotfiles:desktop, dotfiles:host]
  ansible.builtin.lineinfile:
    path: "{{ user_home }}/.config/i3/config"
    regexp: '^bindsym \$mod\+Return exec --no-startup-id /usr/bin/alacritty'
    line: 'bindsym $mod+Return exec --no-startup-id ~/.local/bin/prime-run /usr/bin/alacritty'
  when: "'i3' in (desktop_sessions_enabled | default([]))"
