---
- name: Test safe mode
  hosts: all
  become: true
  vars:
    storage_safe_mode: true
    mount_location1: '/opt/test1'
    mount_location2: '/opt/test2'
    volume_group_size: '10g'
    volume1_size: '5g'
    volume2_size: '4g'
  tags:
    - tests::lvm

  tasks:
    - name: Run the role
      include_role:
        name: linux-system-roles.storage

    - name: Mark tasks to be skipped
      set_fact:
        storage_skip_checks:
          - blivet_available
          - "{{ (lookup('env',
                        'SYSTEM_ROLES_REMOVE_CLOUD_INIT') in ['', 'false']) |
                ternary('packages_installed', '') }}"
          - service_facts

    - name: Get unused disks
      include_tasks: get_unused_disk.yml
      vars:
        min_size: "{{ volume_group_size }}"
        max_return: 1

    - name: Try to install nilfs2 support
      block:
        - name: Install package
          package:
            name: nilfs-utils
            state: present
            use: "{{ (__storage_is_ostree | d(false)) |
                     ternary('ansible.posix.rhel_rpm_ostree', omit) }}"
      rescue:
        - name: Set skip rest true
          set_fact:
            storage_test_skip_rest: true

    - name: Run test if nilfs is available
      when: storage_test_skip_rest is not defined or not storage_test_skip_rest
      block:
        - name: Create nilfs2 partition (1/2)
          command: parted -s /dev/{{ unused_disks[0] }} mklabel gpt
          changed_when: false

        - name: Create nilfs2 partition (1/2)
          command: parted -s /dev/{{ unused_disks[0] }} mkpart primary 0% 100%
          changed_when: false

        - name: Create nilfs2 partition (2/2)
          command: mkfs -t nilfs2 -f /dev/{{ unused_disks[0] }}1
          changed_when: false

        - name: Verify that the play fails with expected error message
          include_tasks: verify-role-failed.yml
          vars:
            __storage_failed_regex: >-
              cannot remove existing formatting .+? and/or devices on
              disk .+?pool .+?in safe mode
            __storage_failed_msg: >-
              Role did not report correct message about making changes in safe
              mode
            __storage_failed_params:
              storage_pools:
                - name: foo
                  disks: "{{ unused_disks }}"
                  volumes:
                    - name: test1
                      size: "{{ volume1_size }}"
                    - name: test2
                      size: "{{ volume2_size }}"

        - name: Cleanup - remove nilfs2 partition
          command: wipefs -a /dev/{{ unused_disks[0] }}
          changed_when: false

    #
    # Clean up.
    #
    - name: Clean up variable namespace
      set_fact:
        storage_test_skip_rest: null
