---
- name: Converge
  hosts: all
  gather_facts: false
  vars:
    idrac_server_powerstate_wait_seconds: "{{ lookup('env', 'idrac_powercycle_wait_seconds') }}"
  tasks:
    - name: Pre-requisite - Server is Power On
      ansible.builtin.import_role:
        name: idrac_server_powerstate
      vars:
        hostname: "{{ lookup('env', 'IDRAC_IP') }}"
        username: "{{ lookup('env', 'IDRAC_USER') }}"
        password: "{{ lookup('env', 'IDRAC_PASSWORD') }}"
        validate_certs: false
        reset_type: "On"
        resource_id: "System.Embedded.1"
      check_mode: false
      tags: molecule-idempotence-notest

    - name: "Waiting after performing Power On operation"
      ansible.builtin.pause:
        seconds: "{{ idrac_server_powerstate_wait_seconds }}"
      when: idrac_server_powerstate_out.changed # noqa: no-handler
      check_mode: false
      tags: molecule-idempotence-notest

    - name: Performing GracefulShutdown on the iDRAC device
      ansible.builtin.import_role:
        name: idrac_server_powerstate
      vars:
        hostname: "{{ lookup('env', 'IDRAC_IP') }}"
        username: "{{ lookup('env', 'IDRAC_USER') }}"
        password: "{{ lookup('env', 'IDRAC_PASSWORD') }}"
        validate_certs: false
        reset_type: "GracefulShutdown"
        resource_id: "System.Embedded.1"

    - name: Asserting GracefulShutdown in check mode
      ansible.builtin.assert:
        that: idrac_server_powerstate_out.msg == "Changes found to be applied."
      when: ansible_check_mode
      tags: molecule-idempotence-notest

    - name: Fetching iDRAC server powerstate after performing GracefulShutdown operation
      ansible.builtin.uri:
        url: "https://{{ lookup('env', 'IDRAC_IP') }}:{{ https_port }}/redfish/v1/Systems/System.Embedded.1"
        user: "{{ lookup('env', 'IDRAC_USER') }}"
        password: "{{ lookup('env', 'IDRAC_PASSWORD') }}"
        validate_certs: false
        headers: 'Accept=application/json'
      register: idrac_server_powerstate_current_powerstate
      until: idrac_server_powerstate_current_powerstate.json.PowerState == "Off"
      retries: 10
      delay: 30
      when: not ansible_check_mode and idrac_server_powerstate_out.changed
      no_log: true

    - name: Asserting GracefulShutdown
      ansible.builtin.assert:
        that:
          - idrac_server_powerstate_out.msg == "Successfully performed the reset type operation 'GracefulShutdown'."
      when: not ansible_check_mode and idrac_server_powerstate_out.changed
