---
- name: Fail if not running Nix
  ansible.builtin.raw: grep Nix /etc/os-release
  changed_when: false

- name: Install Python3 if needed
  ansible.builtin.raw: bash -c "which python3 || nix-env -iA nixos.python3"

- name: Gather facts now that Python is installed
  ansible.builtin.setup:

- name: Find correct device
  ansible.builtin.set_fact:
    device: "{{ item }}"
  when:
    - item.value.host is defined
    - item.value.host != ""
    - item.value.removable|int == 0
  with_items:
    - "{{ ansible_devices | dict2items }}"
  loop_control:
    label: "{{ item.key }}"

- name: Wipe /dev/{{ device.key }} and label GPT
  ansible.builtin.shell:
    cmd: sgdisk -og /dev/{{ device.key }}

- name: Create boot partition
  ansible.builtin.shell:
    cmd: sgdisk -n 1::+500M -t 1:ef00 /dev/{{ device.key }}

- name: Create root partition
  ansible.builtin.shell:
    cmd: sgdisk -n 2::0 -t 2:8300 /dev/{{ device.key }}

- name: Rescan disk
  community.general.parted:
    device: /dev/{{ device.key }}
  register: device

- name: Build prefix
  ansible.builtin.set_fact:
    device_prefix: "{{ device.disk.dev }}{% if 'nvme' in device.disk.dev %}p{% endif %}"

- name: Format boot partition
  community.general.filesystem:
    device: "{{ device_prefix }}1"
    fstype: vfat
    
- name: Format root partition
  community.general.filesystem:
    device: "{{ device_prefix }}2"
    fstype: xfs

- name: Mount root partition
  ansible.builtin.shell:
    cmd: mount {{ device_prefix }}2 /mnt

- name: Create /mnt/boot
  ansible.builtin.file:
    path: /mnt/boot
    state: directory

- name: Mount boot partition
  ansible.builtin.shell:
    cmd: mount {{ device_prefix }}1 /mnt/boot

- name: Generate nix hardware config
  ansible.builtin.shell:
    cmd: nixos-generate-config --root /mnt

- name: Copy configuration.nix
  ansible.builtin.template:
    src: "{{ role_path }}/../kodi-config/templates/configuration.nix.j2"
    dest: /mnt/etc/nixos/configuration.nix
    owner: root
    group: root
    mode: '0644'

- name: Install Nix
  ansible.builtin.shell:
    cmd: nixos-install --no-root-password

- name: Reboot asynchronously
  ansible.builtin.shell:
    cmd: "sleep 5 && /run/current-system/sw/bin/systemctl reboot"
  async: 1
  poll: 0

- name: Wait for the reboot and reconnect
  ansible.builtin.wait_for:
    port: 22
    host: '{{ inventory_hostname }}'
    search_regex: OpenSSH
    delay: 15
    timeout: 60
  delegate_to: localhost
  become: false

- meta: end_host