- name: 'Install mdadm'
  apt: 
    pkg: mdadm

- name: 'Check raid 1 has mount point at /var/lib/postgresql'
  command: /bin/mountpoint -q /var/lib/postgresql/
  register: raid1_mounted
  failed_when: False

- name: 'Configure md raid 1'
  shell: mdadm --create /dev/md0 --raid-devices=2 --level=1 /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_drive-scsi[1,2] --run
  register: "array_created"
  when: ansible_facts['devices']['md0'] is undefined and
        raid1_mounted.rc == 1

- name: 'Get configuration strings for configured raids'
  command: "mdadm --detail --scan"
  register: array_details
  changed_when: false

- name: 'Persist configuration in /etc/mdadm/mdadm.conf '
  lineinfile:
    dest: "/etc/mdadm/mdadm.conf"
    regexp: "^{{ item }}"
    line: "{{ item }}"
    state: "present"
  with_items: '{{ array_details.stdout_lines }}'
  when: array_created.changed
  register: updated_mdadm_conf

- name: 'Updating Initramfs'
  command: update-initramfs -u
  when: updated_mdadm_conf is defined and
        updated_mdadm_conf.changed

- name: 'Format raid1, ext4 filesystem'
  community.general.filesystem:
    fstype: ext4
    dev: /dev/md0

- name: 'Update facts about node.'
  setup:

- name: 'Create postrgresql folder'
  file:
    path: /var/lib/postgresql
    state: directory

- name: 'Setup permanent mountpoint /var/lib/postgresql for raid1'
  ansible.posix.mount:
    path: /var/lib/postgresql
    src: UUID={{ ansible_facts['devices']['md0']['links']['uuids'][0] }}
    fstype: ext4
    state: present
  register: permanent_raid1_mount
    
- name: reboot 
  reboot:
  when: permanent_raid1_mount.changed