- name: Build and Upload NixOS Image, Restore and Convert to Template
  hosts: nodes
  gather_facts: false

  vars:
    flake_name: "{{ flake | default('base') }}"
    image_dir: "{{ playbook_dir }}/../../nixos"
    result_path: "{{ image_dir }}/result"
    dest_dir: "/var/lib/vz/dump/"

  tasks:
    - name: Build NixOS base image
      ansible.builtin.shell: nix build .#{{ flake_name }}
      args:
        chdir: "{{ image_dir }}"
      register: build_result
      delegate_to: localhost

    - name: Get built image file
      ansible.builtin.find:
        paths: "{{ result_path }}"
        patterns: "*.vma.zst"
      register: built_image
      delegate_to: localhost

    - name: Fail if no image was built
      ansible.builtin.fail:
        msg: "No image file found in result/"
      when: built_image.files | length == 0
      delegate_to: localhost

    - name: Set fact for built image path
      ansible.builtin.set_fact:
        local_image_path: "{{ built_image.files[0].path | realpath }}"
        image_filename: "{{ built_image.files[0].path | basename }}"
      delegate_to: localhost

    - name: Copy image to Proxmox
      ansible.builtin.copy:
        src: "{{ local_image_path }}"
        dest: "{{ dest_dir }}"

    - name: Remove local build result
      ansible.builtin.file:
        path: "{{ result_path }}"
        state: absent
      delegate_to: localhost

- name: Restore and Convert to Template on Proxmox
  hosts: nodes
  become: true

  vars_prompt:
    - name: "vmid"
      prompt: "Enter VMID for the template"
      private: no
      default: "9000"

    - name: "vmname"
      prompt: "Enter name for the Proxmox template"
      private: no
      default: "nixos-base"

  vars:
    image_path: "/var/lib/vz/dump/{{ image_filename }}"
    cpu_cores: 2
    memory_mb: 2048

  tasks:
    - name: Restore VM from image
      ansible.builtin.command: >
        qmrestore {{ image_path }} {{ vmid }} --unique true
      args:
        creates: "/etc/pve/qemu-server/{{ vmid }}.conf"

    - name: Set name, CPU and memory
      ansible.builtin.command: >
        qm set {{ vmid }} --cores {{ cpu_cores }} --memory {{ memory_mb }} --name {{ vmname }}

    - name: Convert VM to template
      ansible.builtin.command: qm template {{ vmid }}
