---
- name: Add data disk to VM for pocketid
  community.proxmox.proxmox_disk:
    api_host: "{{ proxmox_api_host }}"
    api_user: "{{ proxmox_api_user }}"
    api_token_id: "{{ proxmox_api_token_id }}"
    api_token_secret: "{{ proxmox_api_token_secret }}"
    vmid: "{{ app_data_disks.pocketid.vmid }}"
    disk: "{{ app_data_disks.pocketid.disk_id }}"
    storage: "{{ app_data_disks.pocketid.storage }}"
    size: "{{ app_data_disks.pocketid.size }}"
    state: present
  delegate_to: localhost
  become: no
  run_once: true
  ignore_errors: yes
  register: disk_result

- name: Display disk creation result
  debug:
    var: disk_result

- name: Wait for data disk to be available
  wait_for:
    path: "{{ app_data_disks.pocketid.device }}"
    state: present
    timeout: 30

- name: Check if data disk is formatted
  command: "blkid {{ app_data_disks.pocketid.device }}"
  register: disk_formatted
  failed_when: false
  changed_when: false

- name: Format data disk with ext4
  filesystem:
    fstype: ext4
    dev: "{{ app_data_disks.pocketid.device }}"
  when: disk_formatted.rc != 0

- name: Create pocketid data mount point
  file:
    path: "{{ app_data_disks.pocketid.mount_point }}"
    state: directory
    mode: "0755"

- name: Mount data disk
  mount:
    path: "{{ app_data_disks.pocketid.mount_point }}"
    src: "{{ app_data_disks.pocketid.device }}"
    fstype: ext4
    state: mounted
    opts: defaults

- name: Create pocketid directory
  file:
    path: /opt/pocketid
    state: directory
    mode: "0755"

- name: Create docker-compose file for Pocket ID
  template:
    src: docker-compose.yml.j2
    dest: /opt/pocketid/docker-compose.yml
    mode: "0644"
- name: Start Pocket ID
  shell: cd /opt/pocketid && docker compose down && docker compose up -d
  args:
    chdir: /opt/pocketid
