---
# yamllint disable rule:line-length
- name: Update platforms
  hosts: localhost
  tasks:
    - name: Filtering platforms list using the group defined in the MOLECULE_GROUP environment variable
      set_fact:
        # eslint-disable-next-line max-len
        molecule_yml: "{{ molecule_yml | combine({'platforms': (molecule_yml.platforms | selectattr('groups', 'contains', lookup('env', 'MOLECULE_GROUP')))}) }}"
      when: ansible_env.MOLECULE_GROUP is defined

- name: Create
  hosts: localhost
  connection: local
  gather_facts: false
  no_log: '{{ molecule_no_log }}'
  tasks:
    - name: Create molecule instance(s)
      vagrant:
        instance_name: '{{ item.name }}'
        instance_interfaces: '{{ item.interfaces | default(omit) }}'
        instance_raw_config_args: '{{ item.instance_raw_config_args | default(omit) }}'
        config_options: '{{ item.config_options | default(omit) }}'
        platform_box: '{{ item.box | default("generic/alpine310") }}'
        platform_box_version: '{{ item.box_version | default(omit) }}'
        platform_box_url: '{{ item.box_url | default(omit) }}'
        provider_name: '{{ molecule_yml.driver.provider.name | default(omit, true) }}'
        provider_memory: '{{ item.memory | default(omit) }}'
        provider_cpus: '{{ item.cpus | default(omit) }}'
        provider_options: '{{ item.provider_options | default(omit) }}'
        provider_raw_config_args: '{{ item.provider_raw_config_args | default(omit) }}'
        provider_override_args: '{{ item.provider_override_args | default(omit) }}'
        provision: '{{ item.provision | default(omit) }}'
        state: up
      register: server
      with_items: '{{ molecule_yml.platforms }}'
      loop_control:
        label: '{{ item.name }}'
      no_log: false

    - name: Run tasks if there were changes while creating the molecule instance(s)
      when: server.changed | bool
      block:
        - name: Populate instance config dict
          set_fact:
            instance_conf_dict:
              instance: '{{ item.Host }}'
              address: '{{ item.HostName }}'
              user: '{{ item.User }}'
              port: '{{ item.Port }}'
              identity_file: '{{ item.IdentityFile }}'

          with_items: '{{ server.results }}'
          register: instance_config_dict

        - name: Convert instance config dict to a list
          set_fact:
            instance_conf: "{{ instance_config_dict.results | map(attribute='ansible_facts.instance_conf_dict') | list }}"

        - name: Dump instance config
          copy:
            content: '{{ instance_conf | to_json | from_json | to_yaml }}'
            dest: '{{ molecule_instance_config }}'
            mode: 0600
