# This is a salf state to replicate nvidia driver installation environment
# for cuda loads.

# HOWTO:
# 1. Check your devices using `qvm-pci list` and set device list in map.jinja
# 2. Check preferences in map.jinja
# 3. Consider which packages you want to install besides drivers, see
#   `nvidia-driver--install`, I install nvtop.
# 4. Consider whether you need to delete `grubby-dummy` - this is a
#  "recent" dependency conflict with some modern nvidia cards.
#  You might not need to do that.

{% from 'nvidia-driver/map.jinja' import prefs,devices,paths %}

# Create qube
{% if grains['id'] == 'dom0' %}

nvidia-driver--create-qube:
  qvm.vm:
    - name: {{ prefs.standalone_name }}
    - present:
      - template: {{ prefs.template_name }}
      - label: {{ prefs.standalone_label }}
      - mem: {{ prefs.standalone_memory }}
      - vcpus: {{ prefs.standalone_cpus }}
      - maxmem: 0
      - class: StandaloneVM
    - prefs:
      - label: {{ prefs.standalone_label }}
      - mem: {{ prefs.standalone_memory }}
      - vcpus: {{ prefs.standalone_cpus }}
      - pcidevs: {{ devices }}
      - virt_mode: hvm
      - kernel:
      - maxmem: 0
      - class: StandaloneVM
    - features:
      - set:
        - menu-items: qubes-run-terminal.desktop

# Start qube and install drivers
{% elif grains['id'] == prefs.standalone_name %}

nvidia-driver--enable-repo:
  cmd.run:
    - name: dnf config-manager --enable rpmfusion-{free,nonfree}{,-updates}

nvidia-driver--extend-tmp:
  cmd.run:
    - name: mount -o remount,size=4G /tmp/

nvidia-driver--remove-grubby:
  pkg.purged:
    - pkgs:
      - grubby-dummy

nvidia-driver--install:
  pkg.installed:
    - pkgs:
      - akmod-nvidia
      - xorg-x11-drv-nvidia-cuda
      - nvtop
    - require:
      - cmd: nvidia-driver--enable-repo
      - cmd: nvidia-driver--extend-tmp
      - pkg: nvidia-driver--remove-grubby

nvidia-driver--assert-install:
  loop.until_no_eval:
    - name: cmd.run
    - expected: 'nvidia'
    - period: 20
    - timeout: 600
    - args:
      - modinfo -F name nvidia
    - require:
      - pkg: nvidia-driver--install

nvidia-driver--remove-conf:
  file.absent:
    - name: {{ paths.nvidia_conf }}
    - require:
      - loop: nvidia-driver--assert-install

{% endif %}
